Borislav Hadzhiev
Tue Apr 19 2022·2 min read
Photo by Soroush Karimi
To use an image as a link in React, wrap the image in an <a>
tag or a Link
tag if using react router. The image will get rendered instead of the link and
clicking on the image will cause the browser to navigate to the specified
page.
import {BrowserRouter as Router, Link} from 'react-router-dom'; export default function App() { return ( <Router> <div> {/* 👇️ react router link */} <Link to="/about"> <img src="https://bobbyhadz.com/images/blog/react-usestate-dynamic-key/thumbnail.webp" alt="example" /> </Link> <br /> <br /> {/* 👇️ Anchor link */} <a href="https://google.com" target="_blank" rel="noreferrer"> <img src="https://bobbyhadz.com/images/blog/react-prevent-page-refresh-on-form-submit/thumbnail.webp" alt="example" /> </a> </div> </Router> ); }
The code snippet shows how to use an image as a link in React for both react router links and native anchor tags.
Under the hood, the Link
component is really just an <a>
tag, so the same
approach applies.
If you need to use an image from the local file system as a link, import the
image and set it to the src
prop of the img
element.
import {BrowserRouter as Router, Link} from 'react-router-dom'; // 👇️ import the image import myImage from './thumbnail.webp'; export default function App() { return ( <Router> <div> {/* 👇️ react router link */} <Link to="/about"> <img src={myImage} alt="example" /> </Link> <br /> <br /> {/* 👇️ Anchor link */} <a href="https://google.com" target="_blank" rel="noreferrer"> <img src={myImage} alt="example" /> </a> </div> </Router> ); }
The image has to be located in the src
directory of your project.
The example above assumes that there is a thumbnail.webp
file in the same
directory as the App.js
component.
If you link to an external URL, make sure to use the <a>
tag and not the
Link
component.
The react router Link
component is intended to only be used for internal
navigation.
When the target
attribute on the a
element is set to _blank
, the external
link is opened in a new tab. You can remove the attribute if you want to open
the external URL in the same tab.