The Complete React-Router Link Tutorial (With MUI)

React-Router is a highly popular routing library. As of the beginning of 2021, it has more than 4 million weekly downloads:

React-Router npm downloads

One of the core pieces of react-router is the Link component. This versatile component has props for customizing routing, passing routing params as objects, styling, history, and more.

Let’s build an app that demonstrates these properties. Since this is a demo of the Link component, the app will be heavy on the Links. We will use Material-UI’s Drawer component to position the React-Router Links on the left side of the UI.

React-Router with MUI Link

Code Sandbox for the app is in the resources section at the end of the article.

React-Router Link `to` Prop

The most basic react-router Link component may look something like this: <Link to="/page1">Page 1</Link> .

However, the to prop can accept more than a string. It can accept an object and an arrow function.

<Link
to={{
pathname: "/page1",
search: "?color=red",
state: { count: count }
}}
>

The above react-router Link to prop sets the pathname, which is what to=“/page1” sets without explicitly stating it. However, the object above also sets a query param (accessible via URLSearchParams(useLocation().search)) and state (accessible via props.location.state?.count). In the Codesandbox demo, the above code can be found on the second Link component in App.js.

Another to prop option is to pass a lambda function:

<Link to={() => `/page4`} text="Page 4" component={H1} />

This is similar to to=“/page4”, but it is useful for setting a variable value as part of the returned string, (for example, () => `/page4?color=${selectedColor}`). The above code can be found in App.js as well.

As info, Links with the “to” prop can be used in buttons, like in this demo, and they can even be added to MUI Alerts and Popovers.

React-Router Link `component` Prop

You may have noticed component={H1} and text=“Page 4" in the above Link code. This is a way for the Link component to be customized in whatever way desired. In App.js of our Codesandbox:

const H1 = (props) => {
const history = useHistory();
return (
<h1
style={{ color: "blue", textDecoration: "underline" }}
onClick={() => {
history.push(`/page4`);
}}
>
{props.text}
</h1>
);
};

This code creates a custom h1 component that can be used with a react-router Link component. Notice that the text prop from the Link code snippet above was passed into the H1 component as props.text. I also had to use the useHistory hook to be able to interact appropriately with react-router.

A common reason to pass a component prop to Link is to have a custom styled link. Another common reason might be to pass a component that interacts with a ref somehow.


Related Reading: Test your JavaScript knowledge with these 50 Difficult JS questions!


React-Router Link `ref` Prop

The refs prop can be used to update the Link component dynamically without causing a rerender:

Updating the text on hover
<Link to="/page2" ref={ref}>
<ListItemText primary="Page 2" />
</Link>//...skip a few lines<Container
style={{
color: "blue",
fontSize: 20,
border: "solid black 1px",
textAlign: "center"
}}
onMouseOver={() => {
setCount(count + 1);
ref.current.querySelector("span").innerText = "Refs!!!";
}}
onMouseOut={() => {
ref.current.querySelector("span").innerText = "Page 2";
}}
>
Hover Counter! Count: {count}
</Container>

When the Hover container is hovered over, the text for the Page 2 link updates. This is accomplished by using the useRef react hook and updating the ref in the onMouseOver/onMouseOut functions of the container.

Refs with Links are commonly used for styling, but many kinds of DOM manipulation can be accomplished.

If you want to learn more about List and ListItem components, read here.

React-Router NavLink

NavLinks are similar to Link components but they have a few more props for adding styling when the NavLink to matches the current URL.

<NavLink to="/page3" activeStyle={{ color: "orange" }}>
<ListItemText primary="Page 3" />
</NavLink>

In the code above, when the URL is at “/page3”, the link text color will be orange.

React-Router NavLink

Pretty straight forward, right?

Another similar prop is activeClassName, which applies a class instead of an inline style when the URL matches.

Some of the remaining NavLink props, exactstrict, and isActive, restrict the rules for determining a URL match.

Resources

Code Sandbox with full React code.

Read here how to dynamically load icons using React-Router query params.

React-Router documentation

Share this post:

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.