React router DOM is a popular library for handling routing in React applications.
What is routing? Routing is the process of determining what content to display based on the URL.
For example, if the URL is /about
, the router should display the About page.
To continue the blog you need to setup a react project and react-router-dom, you can checkout Here and notice how the URL after the domain changes and you should have some knowledge of React, you can learn it Here.
I shifted to NextJs and started to using NextJs router, this blog will also help me whenever I work on a React project.
Setup
Navigating between routes
Now once you have setup the router, you can navigate between routes using the Link
component.
Why not use the anchor tag? The anchor tag will reload the page and if you use router it will not reload the page and will be faster.
And thats it, you have learned how to setup and navigate between routes using react-router-dom.
URL parameters
Parameters are very powerful in routing, they can convey some data through routes. Say you want to display a user profile, you can use the user id as a parameter in the URL.
Now how can you access the parameter in the component?
Query Parameters
Query parameters are key-value pairs added to the end of a URL after a ? symbol. They are commonly used to filter, sort, or pass additional data to a route without changing the URL structure. They can be used using useSearchParams
hook.
Programmatic Navigation
You can also navigate between routes programmatically using the useNavigate
hook.
Handling 404 pages
You can also handle 404 pages by adding a route with a *
path in the router.
All the important aspects of react-router-dom are covered in this blog, the features that are used more frequently are covered here. For more specific features you can always checkout the official documentation. Cheers 🥳