React Router | React Router DOM
Published: 2024-06-21 21:33:00

## What is React Router?

Traditional multi-page web apps have multiple view files for rendering different views, while modern Single Page Applications (SPAs) use component-based views. This necessitates switching components based on the URL, which is handled via routing. Although not all development requirements in React need a third-party library, routing is complex and requires a pre-developed solution for efficient app development.

React Router is the most popular and fully-featured routing library for React SPAs. It is lightweight, has an easy-to-learn API, and offers well-written documentation, making it a go-to choice for implementing routing in React apps. Now maintained by Remix, React Router benefits from active development and support.

Unlike traditional websites where routing requests are sent to the server, React Router allows SPAs to handle all routing on the frontend, eliminating the need for additional server requests for new pages. Routing enables seamless navigation between different parts of an application when a user enters a URL or interacts with elements like links or buttons, thus playing a crucial role in building responsive and user-friendly web applications.

## Use Case of React Router

To create a React application using create-react-app, go to your preferred CMD and type:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nqf157qerwl2w1smof7y.png)

The command will create a React application called router-tutorial. Once the application has been successfully created, switch to the app directory using cd router-tutorial in your code editor terminal.

To use React Router in your application, you need to install it.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z3e5adhvcmuzl50vrwgf.png)
run the command below:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6pr3zxjm38i9448oeb5f.png).

## Create ReactApp

Once your project is set up and React Router is installed as a dependency, open the `src/index.js` in your text editor. Import `BrowserRouter` from `react-router-dom` near the top of your file and wrap your app in a `<BrowserRouter>`.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kgpwzrxnraqd1gjpwiah.png)
Wrapping `<App />` with `<BrowserRouter>` will apply the React Router to the components where routing is needed. That is, if you want to route in your application, you have to wrap the `<App />` application with `<BrowserRouter>`.

- BrowserRouter: For React Router to work, it has to be aware and in control of your application’s location. The `<BrowserRouter>` component makes that possible when you wrap the entire application within it. Wrapping the entire application with `<BrowserRouter>` ensures the use of routes within it.

## Rendering Routes
Now that we have successfully set up React Router, to implement routing in our application, we have to render a route (that is, all the pages or components we want to navigate in our browser). To render our routes, we will set up a route for every component in our application.

Routes: Whenever we have more than one route, we wrap them up in Routes. If the application’s location changes, Routes look through all its child Route to find the best match and render that branch of UI.

Route: Route(s) are objects passed to the router creation function. Route renders a component whenever a user navigates to the component path.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iq16mwvet2uddg5cbvo3.png)

This code sets up a basic React application with routing using React Router. It defines two functional components, Home and About, which display simple messages. The BrowserRouter component enables routing, and the Routes and Route components define the paths for the home and about pages. When a user navigates to the root path '/', the Home component is displayed, and when they navigate to '/about', the About component is displayed. This setup provides the structure for a single-page application (SPA) where navigation between different parts of the app is handled on the client side without full page reloads.

## Multilevel routes

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ml4lpbz7suuvyx5rcb7h.png)

## Another method to achieve nested routes

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yxx7sh9ncu5expc63qx4.png)

<u>Nested Routes:<u>

Parent Route (Account):The Route with path 'account' does not have an element prop, indicating it is used to group child routes.This route serves as a container for the nested routes.

Child Routes: Nested routes under 'account':
'/account/profile' renders the Profile component.
'/account/settings' renders the Settings component.

## Dynamic Route

The e-commerce site uses dynamic routing to handle different categories and specific products. Similar to user-based content sites like blogs or social media, each route has a common structure but displays different content based on the URL parameters. This approach helps in organizing and displaying content efficiently, making the site easy to navigate and manage. This is what's known as dynamic pages and routes.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/00oy32b0xnds4g57au2a.png)

useParams hook is used to access the URL parameters. In this case, it captures the userName parameter from the URL.

 It defines a route with a dynamic segment (:userName), captures the parameter using the useParams hook, and uses it within a component to display personalized content. This approach is useful for scenarios where the content or component behavior needs to change based on URL parameters, such as user profiles, product details, or other similar dynamic pages.

Now let's go ahead and add in our API call.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3n5sl84sdfsb6nr3ks1d.png)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b1lc689dujlo9452hvmv.png)

<u>Home Component</u>

- State Management: Uses the useState hook to store the list of posts.
- Data Fetching: The useEffect hook fetches data from jsonplaceholder.typicode.com/posts when the component mounts and sets the posts state.
- Rendering Posts: Maps over the posts array to create a list of links (NavLink) that navigate to a detailed view of each post. The to prop of NavLink uses a dynamic URL (/post/${post.id}).

<u>PostPage Component</u>

- useParams: Retrieves the postId from the URL.
- State Management: Uses the useState hook to store the fetched post data.
- Data Fetching: The useEffect hook fetches data for the specific post ID (params.postId) whenever params.postId changes.
- Conditional Rendering: Displays a loading message until the data is fetched and then displays the post’s title and body.

<u>Summary</u>

- Home Component: Fetches and displays a list of posts. Each post is a link that navigates to a detailed view of the post.
- PostPage Component: Fetches and displays details of a specific post based on the postId URL parameter.
- React Router: Handles navigation between the home page and the post detail page.