How to use a Button as a Link in React

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Use a Button as a Link in React #

To use a button as a link in React, wrap the button in an <a> tag or a Link component if using react router. The button will get rendered instead of the link and clicking on it 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"> <button>Click</button> </Link> <br /> <br /> {/* 👇️ Anchor link */} <a href="https://google.com" target="_blank" rel="noreferrer"> <button>Click</button> </a> </div> </Router> ); }

react button link

The code snippet shows how to use a button 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 button would cause the browser to navigate to the specified page or route.

This approach also works with custom Button components from third party libraries.

You just have to wrap the Button component in a Link or an <a> tag.

App.js
import {BrowserRouter as Router, Link} from 'react-router-dom'; function Button({children}) { return <button>{children}</button>; } export default function App() { return ( <Router> <div> {/* 👇️ react router link */} <Link to="/about"> <Button>My custom button</Button> </Link> <br /> <br /> {/* 👇️ Anchor link */} <a href="https://google.com" target="_blank" rel="noreferrer"> <Button>My custom button</Button> </a> </div> </Router> ); }

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.