How to Configure Routes in ReactJS with React Router

Learn how to configure routes with React Router.

Picture of Nsikak Imoh, author of Macsika Blog
How to Configure Routes in ReactJS with React Router written on a plain white background
How to Configure Routes in ReactJS with React Router written on a plain white background

In this tutorial, you will learn how to configure routes with React Router.

For this example, we will set up two routes with React Router. The first route is the home route. If the user navigates to http://127.0.0.1:3000/, they should be able to see the home page. And if they visit http://127.0.0.1:3000/about they should be able to see the about page.

If you followed from the previous post where we installed and set up React Router on a React project, you will notice that at the moment in the source folder, we have index.js where we render the app component to the dom.

The app component is present in App.js and contains a very simple UI: react logo and some texts.


import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;
Current state of the React App.js

If we run the project and take a look at the browser, we should be able to see the same being rendered.

How to Configure Routes with React Router

  • Step 1: Import the BrowserRouter component and wrap the <App/> component.

    For that, react router provides a component called BrowserRouter with which we need to wrap our entire app.

    Open the index.js, at the top, insert the code to import the BrowserRouter component from React Router package.

     
      import  {  BrowserRouter  }  from  'react-router-dom'
    
    Import the BrowserRouter component.

    Next, wrap the <App/> Component with the BrowserRouter Component.

    
     import React from 'react'
     import ReactDOM from 'react-dom'
     import { BrowserRouter } from 'react-router-dom'
     import './index.css'
     import App from './App'
     import reportWebVitals from './reportWebVitals'
    
     ReactDOM.render(
       <React.StrictMode>
         <BrowserRouter>
           <App />
         </BrowserRouter>
       </React.StrictMode>,
       document.getElementById('root')
     )
    
     // If you want to start measuring performance in your app, pass a function
     // to log results (for example: reportWebVitals(console.log))
     // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
     reportWebVitals()
    
    Current state of index.js

    What this allows us to do is use all the features from React Router within the app component tree.

  • Step 2: Create the components that will be rendered as a route

    Let’s set up the components that need to be rendered for the app root.

    In the source folder, create a new folder called components. Within this folder, create two files Home.js and About.js.

    Within Home.js, create a very simple function component that renders the text home page.

    
      export const Home = () => {
        return <div>Home Page</div>
      }
    
    Current state of the Home.js.

    Do the same in about.js:

    
      export const About = () => {
        return <div>About Page</div>
      }
    
    Current state of the about.js.

Let’s configure the routes for the route configuration. We need two components from React Router so in App.js, at the top, import Routes and Route from react-router-dom. In the component’s JSX, add the Route component within the Routes component .

  • Step 3: Import the components in App.js and configure the routes.

    Begin by removing the entire component’s code as well as the import statements. Next, define the individual route using the Route component from React Router.

    
     import { Routes, Route } from 'react-router-dom'
     import { Home } from './components/Home'
     import { About } from './components/About'
    
     function App() {
       return (
         <Routes>
           <Route path='/' element={<Home />} />
           <Route path='about' element={<About />} />
         </Routes>
       )
    
    Current state of the App.js.

    First, we import the Routes and Route components from react-router-dom.

    On the Route component, we specify two props the first prop is path that reflects the path in the uURL

    Our first route is the root of the App denoted by a forward slash, hence the value to the path prop is a forward slash path="/". We then tell React Router the element that needs to be rendered when the URL matches this path. In our case, it is the home component. Hence, element={<Home />}.

    We repeat the same for the about but using path="about" and element={<About />}.

    Now, head back to the browser we should see the text home page being rendered. This means the Home component, our first route, works as expected.

    Let’s check the second route, add /about to the URL, you can see the about page being rendered. This means our route configuration is working as expected.

Wrap Off

This is pretty much how you configure routes with React Router let me quickly summarize the steps.

  • We wrap the root component of the app with BrowserRouter from the React Router package and wrapped the App component with it.
  • We create the components that need to be rendered at different URL parts. We created the Home and About components.
  • We configure the routes using the Routes and Route components from React Router at the top level. Each route will accept a path prop that corresponds to the path in the browser URL and the corresponding react element to render when the path is matched.

You might have noticed is that we navigate to the different pages by entering the URL in the browser address bar.

You might have noticed is that we navigate to the different pages by entering the URL in the browser address bar.

This is not how a regular user would navigate in a web application.

Typically, we should have a UI element like a link which the user clicks to navigate to a different route, or the user could also be navigated programmatically to a different route after an action has been completed.

We will do this in the next lesson. Also, we will dive into navigating to different routes using an element.

Get the Complete Code of React Router Tutorials on Github.

Connect with me.

Need an engineer on your team to grease an idea, build a great product, grow a business or just sip tea and share a laugh?