1

I want to build an album app with react native, the main idea is to use a sectionList and show the data in an array like this:

class CustomImage extends Component{ render(){ return( <View> <Image style={styles.Img} source={this.props.imageName} /> <Text style={styles.text}>{this.props.name}</Text> </View> ); } } export default class DisplayAnImage extends Component { render() { return ( <View> <SectionList sections={[ {titile: 'small soldier', data: ["./gifs/2.gif", "./gifs/3.gif", "./gifs/4.gif"]} ]} renderItem={({item}) => <CustomImage name={item} fromWeb={false} imageName={require(item)} />} renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>} /> </View> ); } } 

Above code was indented to make it work inspirited by this answer

I have already put the gifs folder under the project folder, and if I using a static string as source={require(url)} in the Image component, things will work, but when the url came out of an array items iteration, it will not work.

How can I make this work with react native?

EDIT

Don't know if I could edit to make it more specificly, the really thing I want to do is to use a generated array like this:

function numberRange(start, end){ return new Array(end-start).fill().map((d,i) => { var url = "./gifs/" + ( i+start) + ".gif"; return require(url) }); } export default class DisplayAnImage extends Component { render() { return ( <View> <SectionList sections={[ {title: 'small soldier', data: numberRange(2,30)}, {title: 'small soldier', data: numberRange(31,60)} ]} renderItem={({item}) => <CustomImage name={item} fromWeb={false} imageName={item} />} renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>} /> </View> ); } } 

Don't know if have a way to use this array generator to make an array or I have to enter the path one by one on bare hand :-(

1 Answer 1

1

require is a javascript keyword with a preload nature.

And, images will not related to path at runtime --- provide a path to it will not get anything. it becomes bundle resources, so with console.log you can only see resource token related to bundle ex: _1 _2.

It will not work even change require("./gifs/1.gif") to require("./gifs/"+"1.gif").

Try this:

data: [require("./gifs/2.gif"), require("./gifs/3.gif"), require("./gifs/4.gif")] 
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, Val, thanks, it works, already accept that, and don't know if it is properly to ask, actually the data array was generated by a generator, is there a way to work through that? check the edit, thanks.
@armnotstrong just modified my answer with image -> bundle resources relation. Since file path has no meanings at runtime, and after tried many ways with no success, I don't think it's possible...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.