React Router - Links and NavLinks

Understanding Links in React Router

In React, you can create links to your frontend routes using the Link and NavLink components provided by react-router-dom. These components enable navigation without full-page reloads, maintaining a smooth user experience.

Learning Goals

By the end of this reading, you should be able to:

Creating a Link

The Link component creates a navigable link in a React application.


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

function Example() {
  return (
    Create a Team!
  );
}
    

A Link ultimately resolves to an <a href> tag but prevents a full-page reload. Instead, it updates the browser’s history and location, ensuring a seamless navigation experience.

Relative vs. Absolute Paths

The to prop determines the target route:

Relative Path


function Teams() {
  return Create a Team!; // Takes user to `/teams/new`
}
    

Absolute Path


function Teams() {
  return Create a Team!; // Takes user to `/teams/new`
}
    

Relative paths extend the parent component’s route, making nested routing more flexible. Absolute paths always start from the root of the application.

Using NavLink for Active Navigation

The NavLink component behaves like a Link but includes automatic styling for active and pending states.


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

function Navigation() {
  return (
    
  );
}
    

By default, a NavLink adds an active class to the link when its to prop matches the current URL.

Limiting Active State with the end Prop

A NavLink remains active as long as its to prop matches the beginning of the current URL. This means /teams will also be active at /teams/1. To prevent this, use the end prop:



    

Now, the Teams link will only be active at /teams, but not at /teams/1.

Important: Links Must Be Inside a Router

Links and NavLinks will only work if they are inside a router. Attempting to use them outside of a RouterProvider or its enclosed components will produce an error.

What You Have Learned

In this reading, you learned how to:

Further Exploration

To deepen your understanding, explore these topics:

Conclusion

The Link and NavLink components enable smooth navigation in React applications. By mastering them, you can create seamless, dynamic, and user-friendly web experiences.