DynamicRoutes
Let us first understand what dynamic routes are. Dynamic route means the route that we did not know before. They are created dynamically based on any variable or parameter and are non-static and numbers can reach thousands and millions.
for example, this youtube video link:
https://youtube.com/watch/[some video id]
Now this video ID will be different for every video. So such routes are dynamic routes.
To set up dynamic routes, let’s take an example. Suppose there are many contacts in the contact page and each contact has a unique ID. We will just use this unique ID and create pages for all contacts with just one route.
We can write a path like this
path: "/contact/:id"
Example 3: Look at the below code for a better understanding
Javascript
// ContactCard.js import { useParams } from "react-router-dom" const ContactCard = () => { const { id } = useParams(); return ( <h1>Contact id: {id}</h1> ) } export default ContactCard |
Javascript
// index.js import React from 'react' import ReactDOM from 'react-dom/client' import App from './App' import { RouterProvider, createBrowserRouter } from 'react-router-dom' import Home from './Home' import About from './About' import Contact from './Contact' import Founder from './Founder' import Company from './Company' import ContactCard from './ContactCard' const router = createBrowserRouter([ { path: '/' , element: <App />, children: [ { path: '/' , element: <Home />, }, { path: '/about' , element: <About />, children: [ { path: "about-founder" , element: <Founder /> }, { path: "about-company" , element: <Company /> } ] }, { path: '/contact' , element: <Contact />, }, { path: "/contact/:id" , element: <ContactCard /> } ] } ]); ReactDOM.createRoot(document.getElementById( 'root' )).render( <React.StrictMode> <RouterProvider router={router}> <App /> </RouterProvider> </React.StrictMode> ) |
Output:
How to setup React Router v6 ?
React Router is an amazing library that was created by Remix. The purpose of React Router is to enable Client-Side routing in the React application, that is, by using React Router we can create different routes in our React app and can easily navigate to different pages without even reloading the page.
Client-side routing, facilitated by React Router, enables changing routes without page reloads, creating single-page applications (SPAs). React Router efficiently manages what is displayed on each route, making it a powerful and user-friendly library for seamless navigation in React applications.
We will discuss the following setup approach and different methods of React Router v6 in this article:
Table of Content
- Approach to setup React Router in Application
- Steps to set up React Router
- Implementation of React Router v6
- Nested Routes
- useNavigate()
- DynamicRoutes
- createRoutesFromElements
Contact Us