Skayabd
Skayabd

Reputation: 23

React Native dynamic Image in Flatlist

Beginner question here so go easy. I've been trying to render some Images inside my flatlist, using urls from: https://jsonplaceholder.typicode.com/photos I tried first with the titles inside a text and it seems to be working. but when I tried with the urls it didn't work, my code:

export default function Home() {
     const [data, setData] = useState([]);
      useEffect(() => {
        fetch('https://jsonplaceholder.typicode.com/photos')
          .then((res) => res.json())
          .then((response) => setData(response))
          .catch((error) => {
               console.log(error);
             });
      });
     return (
        <View style={styles.containermainstyle}>
          <View style={styles.headerstyle}>
            <TextInput style={styles.inputstyle} placeholder={'product...'} />
            <TouchableOpacity>
              <Text>Filtres</Text>
            </TouchableOpacity>
          </View>
          <View style={styles.mainstyle}>
            <FlatList
              data={data}
              renderItem={({ item }) => {
              <View style={{flex:1, flexDirection: 'row'}}>  
                <Image
                  style={styles.imagestyle}
                  source={{uri: item.url }}
                />;
              </View>
              }}
            />
          </View>
        </View>
      );
    }

Upvotes: 2

Views: 2129

Answers (1)

Denis Tsoi
Denis Tsoi

Reputation: 10414

render iphone

Seems like your renderItem function is incorrect as it is missing a return (<JSX />)

instead of...

({ item }) => {
<View style={{ flex:1, flexDirection: 'row' }}>  
  <Image
    style={styles.imagestyle}
    source={{ uri: item.url }}
  />;
</View>
}

it should be

({ item }) => {
  return (
  <View style={{ flex:1, flexDirection: 'row' }}>  
    <Image
      style={styles.imagestyle}
      source={{ uri: item.url }}
    />
  </View>
  )
}

Also note, useEffect should have an empty dependency array if you dont' want to constantly refetch.

Example Fix

import React, { useState, useEffect } from "react"
import { View, Image, FlatList, Text, TouchableOpacity } from "react-native"

export default function App() {
  const [data, setData] = useState([])
  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/photos")
      .then((res) => res.json())
      .then((response) => {
        setData(response)
      })
      .catch((error) => {
        console.log(error)
      })
  }, [])

  const renderItem = ({ item }) => {
    console.log(item)
    return (
      <View style={{ flex: 1, flexDirection: "row" }}>
        <Image style={{ height: 100, width: 100 }} source={{ uri: item.url }} />
      </View>
    )
  }

  return (
    <View>
      <View>
        <FlatList data={data} renderItem={renderItem} />
      </View>
    </View>
  )
}

Upvotes: 2

Related Questions