Use an Image as a Link in React.js

avatar

Borislav Hadzhiev

Last updated: Apr 19, 2022

banner

Photo from Unsplash

Use an Image as a Link in React.js #

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.

App.js
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.

Clicking on the image would cause the browser to navigate to the specified page or route.

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.

App.js
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> ); }
Make sure to specify the correct path to the image file (including the extension).

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.