Skip to main content

React Routing

React Router

Traditional multi-page web application uses server based routing where the user requests for a page, the request goes to the server, and when they navigate through different parts of the web page it a new request will be sent to the server to request for a new page. The browser will basically request new web page everytime the user interacts with the web page.

That's the traditional MPA model, on the other hand, Single Page Application model uses client side routing that basically loads in only single HTML page. When the user navigates to a different route, React Router will intercept the URL and update the browser history without re-requesting the request to the server. The page is dynamically updated with the corresponding component based on the route. The web application will only request API to the server for data to populate for the web page. This improves user experience because it doesn't need to go to the server for every navigation.

React Router isn't package by default from the core library and in order to leverage it you will need to install it into your React application.

npm install react-router-dom

How to Implement Routing

To implement routing you would need couple components to manage the user's navigation history.

BrowserRouter

This component is the backbone of React Router, it will keep your UI in sync with the URL. So whenever you make changes to the URL it will result in the correct corresponding component being rendered. This means that any navigation will result also in browser history allowing the user to easily go back or go forward in their page history.

Under the hood, this component uses the HTML 5 History API which consists of pushState, replaceState, popState to monitor and manipulate the application's browsing history.

To leverage this component you would wrap your entire application in BrowserRouter component in order to give React Router the control of your application and enable routing correctly.

app.render(
    <BrowserRouter>
        <Content />
    </BrowserRouter>
);

In this simple example, we have wrapped our main web application with BrowserRouter enabling the routing capability for our application.

Routes and Route

These two components are used to group all of the app's routes. Each Route is used to specify a path to the React component that you would like to render when the URL matches to the given path.

As a example you can define routing to your web application like such:

app.render(
    <BrowserRouter>
        <Routes>
            <Route path="/" element={<MainPage />} />
            <Route path="/about-me" element={<SidePage />}/>
        </Routes>
    </BrowserRouter>
);

The