'Flatlist Image source in React Native
I am trying to render a FlatList in React Native that it will be like an image carousel.
I want to provide the image sources in the assets folder and pass each items source in the renderItem but i get error undefined is not an object.
Here is the state:
export default function App() {
const [images, setimages] = useState([
{src:require('./assets/image1.png'),key:'1'},
{src:require('./assets/image2.png'),key:'2'},
{src:require('./assets/image3.png'),key:'3'},
{src:require('./assets/image4.png'),key:'4'},
{src:require('./assets/image5.png'),key:'5'}
]);
And here is the FlatList:
<FlatList
horizontal={true}
showsHorizontalScrollIndicator={false}
data={images}
renderItem={ ({images}) => (
<Image source={images.src} style={{
width:260,
height:300,
borderWidth:2,
borderColor:'#d35647',
resizeMode:'contain',
margin:8
}}></Image>
)}
/>
Solution 1:[1]
This is happening because you're trying to destructure a images parameter which doesn't exist, it's called item.
Try this instead:
return (
<FlatList
horizontal
showsHorizontalScrollIndicator={false}
data={images}
renderItem={({ item }) => (
<Image
source={item.src}
style={{
width:260,
height:300,
borderWidth:2,
borderColor:'#d35647',
resizeMode:'contain',
margin:8
}}
/>
)}
/>
);
Solution 2:[2]
the comment above is correct, however there is the uri attribute inside the source where you assign the url of the image see:
return (
<FlatList
horizontal
showsHorizontalScrollIndicator={false}
data={images}
renderItem={({ item }) => (
<Image
source={{ uri: item.src }}
style={{
width:260,
height:300,
borderWidth:2,
borderColor:'#d35647',
resizeMode:'contain',
margin:8
}}
/>
)}
/>
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | emeraldsanto |
| Solution 2 | Maou Yami |
