Adding a Link to a Bootstrap Button with React Router

import { Link } from “react-router-dom”;
import Button from "react-bootstrap/Button";
...<Link to="/about">
<Button variant="outline-light" size="lg">
about
</Button>
</Link>

The Issues

While this code technically worked and linked to the page I wanted, it wasn’t ideal for two reasons. The first issue was that it added a blue underline to the button text while hovering. While this can be fixed using CSS, it isn’t ideal.

<a href="/about">
<button type="button" class="btn">
about
</button>
</a>

The Solutions

There are two good solutions to this that I found. The first, and the one that I ultimately went with, is to use hooks. Even if you’re not yet familiar with React Hooks, I promise this will be easy to implement.

useHistory Hook

React Router now comes with some built in hooks that according to their documentation “let you access the state of the router and perform navigation from inside your components.” Note: you must be using React 16.8 or higher to use these hooks.

import { useHistory } from "react-router-dom";
import Button from "react-bootstrap/Button";
...function HomeSectionMain() {
const history = useHistory();
function handleClick(path) {
history.push(path);
}
return (
<Button
variant="outline-light"
size="lg"
onClick={() => handleClick("about")}
>
about
</Button>
)
}
<button
type="button"
class="btn btn-outline-light btn-lg"
>
about
</button>

Going the CSS route

While the previous solution worked great for me, there is another solution I came across on Stack Overflow as well. This option styles the <Link> to match the button style, which has the advantage of being more semantic, and doesn’t require you to add an extra clickHandler() function.

<Link 
className="btn btn-outline-light btn-lg"
role="button"
to="/about"
>
about
</Link>

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Arthur Wilton

Arthur Wilton

41 Followers

Software Developer and Video/Post Production Professional. Recent graduate of Flatiron School.