Understanding React Router

Hey everyone, welcome you all. today we’re diving into ReactRouter, an important library for handling the navigation in React Apps.
So ReactRouter allows you to add multiple pages or views to your app and manages routing between them seamlessly.
Key Features of React Router JS
Declarative Routing: React Router uses a declarative approach, meaning you define the routes and let React handle the navigation and rendering of components when users navigate to different URLs.
SPA Navigation: As part of single-page applications, React Router allows the app to update its view dynamically without reloading the page, leading to a smoother user experience.
Nested Routes: You can nest routes within each other to create more complex layouts and structure your app with ease.
Dynamic Routing: React Router makes it easy to pass dynamic parameters in URLs, enabling you to load components based on those parameters (like user profiles or product pages).
Why do we need it?
If you look at the reference images below, the same page appears at every URL, making the path irrelevant.
How to use React Router.
After creating your vite project from npm
Step 1: Install React Router from npm
npm i react-router
Step 2: render a <BrowserRouter> around your application
Check out the reference image for a better understanding of the implementation.(Read the text on the image highlighted in red.
How it changes our app:
Now, the path becomes relevant. Any other path not handled by the router will show a 404 error.
Check out the reference image for a better understanding of the implementation.
Explanation:
Link:
The Link
component is used to create clickable links in your app. Unlike traditional HTML links, it doesn't reload the page; it just updates the view based on the new route.
to:
The to
prop inside Link
specifies the destination path. When a user clicks the link, it navigates to the specified route. For example, clicking the "Home" link navigates to the root path (/), and the "About" link navigates to /about.
Conclusion
React Router is a vital library for React developers aiming to build dynamic, efficient, and user-friendly single-page applications (SPAs). With its straightforward routing solutions, React Router ensures smooth transitions between components, significantly enhancing the user experience. Whether you're working on small-scale projects or more complex, multi-page applications, React Router offers the flexibility and capabilities needed for seamless navigation. Its advanced features, such as dynamic routing and nested routes, make it an essential tool for modern web development.
Subscribe to my newsletter
Read articles from Ankur gurung directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
