I have the following React component, called Profile, which imports and displays a specified profile image. The link to the profile image is provided in it's props.
const Profile = ({name}) => (
<div>
<img src={require(`./images/${name}.png`)} alt="" />
{/* Rest of component goes here */}
</div>
)
For now, I use Node.js's require to dynamically import the profile image, and it works.
I learnt that mixing Node.js's require and ES6's import is generally considered bad practice, so I am looking for a way to use ES6's dynamic import() syntax to achieve the same effect.
Here's what I tried:
const Profile = ({name}) => {
const [image, setImage] = useState("")
useEffect(()=>{
import(`./images/${name}.png`).then(image => {
setProfileImage(image.default)
})
}, [name])
return (
<div>
<img src={require(`./images/${name}.png`)} alt="" />
{/* Rest of component goes here */}
</div>
)
}
It doesn't work at all. The dev build renders the <img /> with no src attribute.
Please provide a solution. Thank you.