DEV Community

Geetika Bajpai
Geetika Bajpai

Posted on

React Router | React Router DOM

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

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
run the command below:

Image description.

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
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

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

Another method to achieve nested routes

Image description

Nested Routes:

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

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
Image description

Home Component

  • 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}).

PostPage Component

  • 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.

Summary

  • 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.

Top comments (0)