'Is there a way to accept image as props in react component?
I am following react tutorial teaching by Bob Zirol in freecodecamp; in my App.js I have rendered a Card.js component which I passed an image as props; so how can I accept the image in my Card.js as props; because I did try several times without valid output; what I tried look like src={require('./images/$(props.img)')} but all didn't work. But the other text props I passed worked correctly
Solution 1:[1]
You can pass the image data as a prop the same way you would pass any other sort of data. From your comment below the question, it seems the image data you're trying to pass is katie-zaferes.png
.
Pass the prop from the parent component to the child component:
import img from '/images/katie-zaferes.png'
const ParentComponent = () =>
{
...
return <Card image = {img} />
}
Retrieve the prop in the child component:
const Card = (props) =>
{
// /images/katie-zaferes.png
const { image } = props
...
}
You can also just import the image directly into the child component, if that fits the structure of your project.
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 | pez |