React Router: A Beginner's Guide with Examples
React Router is a popular, open-source library for handling routing in React applications. It allows you to create single-page applications (SPAs) with multiple views or pages, all while keeping the URL in sync with what's being displayed on the screen.
In this tutorial, we'll cover the basics of React Router and how to set it up in your React application.
Prerequisites
Before you start working with React Router, you should have a basic understanding of React and have an application already set up. If you haven't done so yet, visit this tutorial first to create a new React application.
Installation
To get started with React Router, we'll need to install it as a dependency within our React project. We can use either npm or yarn to accomplish this. Just open your terminal and navigate to your project's root directory:
# Using npm
npm install react-router-dom
# Using yarn
yarn add react-router-dom
Setting Up Routes
Now that we've installed React Router, we can start setting up routes within our application. Routes define which React components should be rendered for specific URLs. Typically, you would define your routes in the main component of your application, such as App.js
.
To import the necessary components from react-router-dom
, add the following code snippet:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
Next, we'll wrap our entire application with the Router
component. This is where React Router will manage the routing of our app:
function App() {
return (
<Router>
/* Application content here */
</Router>
);
}
Inside the Router
, we'll use the Switch
component to define our routes. The Switch
component ensures that only one route is rendered at a time:
function() {
return (
<Router>
<Switch>
/* Define routes here */
</Switch>
</Router>
);
}
Finally, we can define individual routes using the Route
component. Each Route
should specify a path
and the component
to be rendered when the URL matches that path.
In this example, we'll set up three routes:
/
- A homepage/about
- An about page/contact
- A contact page
import Home from './components/Home';
import About from './components/About';
import Contact from './components/Contact';
function App() {
return (
<Router>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</Router>
);
}
Navigation
Now that the routes are defined, we need to create a way for users to navigate between them. Reach Router provides a Link
component for this purpose.
First, we'll import the Link
component from react-router-dom
:
import { Link } from 'react-router-dom';
Then, we'll use the Link
component to create navigation links in our application:
function App() {
return (
<Router>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
</nav>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</Router>
);
}
The to
prop in the Link
component specifics the path to navigate to when the link is clicked within the application. This keeps your app's navigation in sync with the URL.
Accessing Route Parameters
Sometimes, you may need to access route parameters, like dynamic IDs, in your components. React Router makes this easy by allowing you to define dynamic routes.
To do this, we'll add a path
parameter placeholder :id
, that can match any value in the URL matching this format:
<Route path="/user/:id" component={UserProfile} />
We'll then access the route parameter in the component using the useParams
hook or withRouter
HOC (Higher Order Component) if you're using class components:
import { useParams } from 'react-router-dom';
function UserProfile() {
const { id } = useParams();
return (
<div>
<h2>User Profile</h2>
<p>User ID: {id}</p>
</div>
);
}
Redirects
You can also set up redirects using the Redirect
component. In this example, if the user visits "/old-url", they will be redirected to "/new-url."
import { Redirect } from 'react-router-dom';
function App() {
return (
<Router>
<Switch>
<Route path="/old-url">
<Redirect to="/new-url" />
</Route>
<Route path="/new-url" component={NewPage} />
</Switch>
</Router>
);
}
Nested Routes
React Router also supports nested routes, allowing you to create more complex layouts with multiple levels of navigation.
To accomplish this, we'll define our nested routes by placing a Switch
component within another Route
. In this example, the Dashboard
component will serve as a layout for the nested routes:
<Route path="/dashboard">
<Dashboard>
<Switch>
<Route path="/dashboard/profile" component={Profile} />
<Route path="/dashboard/settings" component={Settings} />
<Route path="/dashboard/messages" component={Messages} />
</Switch>
</Dashboard>
</Route>
Programmatic Navigation
Sometimes, you may need to navigate to a different route programmatically. You can use the history
object provided by React Router for this purpose:
import { useHistory } from 'react-router-dom';
function MyComponent() {
const history = useHistory();
const handleClick = () => {
history.push('/new-route');
};
return (
<div>
<button onClick={handlineClick}>Go to New Route</button>
</div>
);
}
Wrapping Up
React Router is a powerful library for handling routing in your React applications. By following the steps outlined in this tutorial, you can set up routes, navigation, route parameters, redirects, and nested routes. With React Router, you can create dynamic and interactive user experiences by managing the navigation of your application effectively.