“Getting Started with React Router”

Benjamin
2 min readJan 21, 2023

--

React Router is a powerful library for handling client-side routing in a React application. In this tutorial, we will learn how to use React Router to create dynamic and nested routes and handle route parameters and redirects.

First, we need to install React Router by running the following command in the terminal:

npm install react-router-dom

Once React Router is installed, we can import it into our application’s entry point (usually index.js).

import { BrowserRouter as Router, Route } from 'react-router-dom';

To create a basic route, we will use the <Route> component provided by React Router. The path prop tells the router which path to match, and the component prop tells the router which component to render when the path is matched.

<Router>
<Route path='/' component={HomePage} />
</Router>

To create nested routes, we can use the <Route> component inside another <Route> component. For example:

<Router>
<Route path='/' component={HomePage}>
<Route path='/about' component={AboutPage} />
<Route path='/contact' component={ContactPage} />
</Route>
</Router>

To handle route parameters, we can use the :param syntax in the path prop. For example, to create a route that matches a user's profile, we can use the following code:

<Router>
<Route path='/user/:username' component={UserProfile} />
</Router>

To access the route parameters, we can use the match object passed down by React Router. For example, to access the username parameter, we can use match.params.username

function UserProfile({ match }) {
const { username } = match.params;
return <h1>Hello, {username}!</h1>;
}

For handling redirects, we can use the <Redirect> component provided by React Router. The to prop tells the router where to redirect the user, and the from prop tells the router which path to match before redirecting.

<Router>
<Route path='/' component={HomePage} />
<Redirect from='/old-path' to='/new-path' />
</Router>

In conclusion, React Router is a powerful library that easily handles client-side routing in a React application. With its ability to create dynamic and nested routes, and handle route parameters and redirects, it becomes a go-to solution for routing in React applications. With this tutorial, you should now understand how to get started with React Router and implement it in your application.”

--

--