Rendering Array of Images in React [duplicate]
I need help. I have been searching similar posts, but none of them solved my problem (imagesPool.js)
import React from 'react';
const imagesPool = [
{ src: './images/starbucks.png'},
{ src: './images/apple.png'},
{ src: './images/mac.png'}
];
export default imagesPool;
Rendering the images (App.js) :
import React from "react";
import imagesPool from './imagesPool';
const App = () => {
return (
<div>
<img src={imagesPool} />
</div>
)};
export default App;
Result : No images being displayed
Solution 1:
You should loop through your images because src
expects a string location to the image.
import imagesPool from './imagesPool';
const App = () => {
return (
<div>
{imagesPool.map((imgSrc, index) => (<img src={imgSrc.src} key={index} alt="Make sure to include a alt tag, because react might throw an error at build"/>))}
</div>
)};
Solution 2:
In react you solve things like conditionals, iterating, etc. with javascript (Remember, <img>
is also just javascript and gets parsed into React.createElement("img")
).
Since img
expects a string in the src
-property, we need to iterate over the array of sources and produce an img
-Element for every source:
<div>
{
imagesPool.map(({ src }) => (<img key={src} src={src} />))
}
</div>
With key
you tell react how to recognize that an element is the same with subsequent renderings.
Solution 3:
You always need to import React from 'react' if you are rendering jsx/tsx. In your code, you are returning jsx, thus you need to import react.
import React from 'react';
import imagesPool from './imagesPool';
const App = () => {
return (
<div>
{imagesPool.map((image) => <img key={image.src} src={image.src} />)}
</div>
)};
export default App;