Search code examples
javascriptreact-nativereact-native-flatlistreact-native-sectionlist

React Native SectionList Images from JSON


I'm having some trouble rendering an image onto a section list from a JSON file even though I am having no trouble with the text data.

here is my JSON DATA:

   {
      "title" : "Friday",
      "data": 
      [
         {
            "artist": "artist 1",
            "stage": "The Oak",
            "Instagram": "insta",
            "Spotify": "spot",
            "date": "10/8/2021",
            "Image": "../assets/art1.jpg",
            "Time" : "4:30PM - 5:00 PM"
         },
         {
            "artist": "artist 2",
            "stage": "The Oak",
            "Instagram": "insta",
            "Spotify": "spot",
            "date": "10/8/2021",
            "Image": "../assets/art2.jpg",
            "Time" : "5.00PM - 5:30 PM"

         }
         
      ]},

I am aware that you have to use the require function to render it but I just cant seem to get it right.

Here is the SectionList:

 <SectionList
      sections={data}
      keyExtractor={(item, index) => index.toString()}
      renderItem={({ item }) => (<View style={styles.listItemView}>
        <Image style={styles.image} source={require(item.Image)} />

        <View>
          <Text style={styles.listItem}>{item.artist}</Text>
          <Text style={styles.listItemTime} >{item.Time}</Text>
        </View>
      </View>)}
      renderSectionHeader={({ section }) => (
        <View style={styles.item}>
          <Text style={styles.title}>{section.title}</Text>
        </View>)}
    />

Any help is welcome. Please let me know if I need to add addition info!

Thanks!


Solution

  • You can use a if-else or switch statement to get the image you want to use.

    const getArtImage = (artName) => {
      switch (artName){
        case 'art1':
          return require('../assets/art1.jpg');
    
        case 'art2':
          return require('../assets/art2.jpg');
    
        default:
          return require('../assets/defaultArt.jpg');
      }
    }
    

    and use this getArtImage function in your Image component.

    <Image style={styles.image} source={getArtImage(item.Image)} />
    

    item.Image should be like art1, art2 etc.

    --

    If your json is a local file, you can convert it to a js file.

    export default {
      title: "Friday",
      data: [
        {
          artist: "artist 1",
          stage: "The Oak",
          Instagram: "insta",
          Spotify: "spot",
          date: "10/8/2021",
          Image: require("../assets/art1.jpg"),
          Time: "4:30PM - 5:00 PM",
        },
        {
          artist: "artist 2",
          stage: "The Oak",
          Instagram: "insta",
          Spotify: "spot",
          date: "10/8/2021",
          Image: require("../assets/art2.jpg"),
          Time: "5.00PM - 5:30 PM",
        },
      ],
    };