I want my images from a React component to open in a new Tab on click.
One of the main problems is that I don’t know how to pass image src to the function (src is passed through prop "picture")
` src={require(picture)}
I found this solution, but can’t really get it to work
const openInNewTab = (url) => {
const newWindow = window.open(url, '_blank', 'noopener,noreferrer')
if (newWindow) newWindow.opener = null
}
and on the image
onClick={() => { openInNewTab(url) }}
>Solution :
You’re overcomplicating this, instead of creating a function, just wrap the img within an a tag with the image’s src attribute as the href attribute. And make it open in a new window by setting the attribute target to _blank. Example:
<a href="https://picsum.photos/200/300" target="_blank">
<img src="https://picsum.photos/200/300" width="200" height="300"/>
</a>
By doing this you also improve the accesssibility of your application.