What is the React Router?

As you already know we create single-page applications with React but to be able to create multi-page apps with React, we need to set up our app to change the component that we render on the screen based on the URL we have. But if we want to achieve this by creating everything by ourselves, it’ll take so much effort and hassle. At this point, the React Router library is here to help us create multi-page applications with React.

How does it work?

First of all, as we do with all frameworks and libraries, we should install it in our project. To do that we should run the comment down below within our app folder.

npm install react-router-dom

And then we start using it by importing the required react-router-dom components, hooks etc. in our components.

Example

import { createBrowserRouter, RouterProvider } from 'react-router-dom'

const router = createBrowserRouter([ // we first need to create a router in our entry point, main component and we can create our routes by simply creating an route object which is required by router method that we use
  {
    path: '/',
    element: <HomePage/>,
  },
  {
    path: '/secondPage',
    element: <SecondPage/>,
  },
])

const App = () => {
  return <RouterProvider router={router} /> // then we need to provide that router to our app to navigate between the routes
}
export default App

So with the setup, react router will handle all the routing for us and it’ll render the required component based on the URL. We still creates a single page app acting like multi page by the help of react router.