Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Image onClick open in new Tab in React

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading