How to Use an Image as a Link in React

Last updated on November 19, 2022
How to Use an Image as a Link in React

Related: How to Link an Image in React

To use an image as a link in React, wrap the image in an anchor (a) tag. Clicking an image link will make the browser navigate to the specified URL.

For example:

App.js

import cbLogo from './cb-logo.png';

export default function App() {
  return (
    <div>
      Click the logo to navigate to the site
      <br />
      <br />
      <a href="https://wp.codingbeautydev.com" target="_blank" rel="noreferrer">
        <img src={cbLogo} alt="Coding Beauty logo"></img>
      </a>
    </div>
  );
}
The browser navigates to the URL when the image link is clicked.
The browser navigates to the URL when the image link is clicked.

We use an import statement to link the image into the file, and assign it to the src prop of the img element to display it.

The properties set on an a element will work as usual when it wraps an image. For instance, in the example, we set the a element's target property to _blank, to open the URL in a new tab. Removing this will make it open in the same tab as normal.

We also set the rel prop to noreferrer for security purposes. It prevents the opened page from gaining access to any information about the page from which it was opened from.

For React Router, you can use an image as link by wrapping the image in a Link element.

For example:

ImagePages.jsx

import { Link } from 'react-router-dom';

export default function ImagesPage() {
  return (
    <div>
      <Link to="/nature" target="_blank" rel="noreferrer">
        <img src="/photos/tree-1.png" alt="Nature"></img>
      </Link>
    </div>
  );
}
Coding Beauty Assistant logo

Try Coding Beauty AI Assistant for VS Code

Meet the new intelligent assistant: tailored to optimize your work efficiency with lightning-fast code completions, intuitive AI chat + web search, reliable human expert help, and more.

See also