Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 22, 2022 09:03 am GMT

Dynamic Routes in React

Hello Everyone today i will be discussing about Dynamic Routes in React JS.I will be using react-router-dom library as it is easy to use and flexible and can be used for both client and server side routings

Let's get started...

Setting the Routing Part -


import { BrowserRouter as Router } from 'react-router-dom'.. <Router>      <App /> </Router>..
  • In your index.js file ,Import the Router component and wrap the App component inside Router component.

Creating the Routes -


import React from 'react';import { Routes, Route, Link } from 'react-router-dom';import UserDetails from './UserDetails';import './App.css';function App() {  const users = [1,2,3,4,5,6,7,8,9,10];  return (    <div className="">      <div className="mx-20 flex gap-5 my-24">        { => {            return (              <Link to={`users/${user}`}>User {user}</Link>            )          })        }      </div>      <Routes>        <Route path="users/:userId" element={<UserDetails />} />      </Routes>    </div>  );}export default App;
  • First we have imported the Routes, Route and Link from react-router-dom.
  • Routes is used to wrap all the Route component inside it.
  • Route is used to specify which component will be rendered at a particular path or url, path is provided using "path" attribute and component is provided using "element" attribute.
  • Link is used to redirect the user to the path provided in the link using "to" attibute.We made the Link dynamic using template string and map the values of user array to the Link componenet with 1-10 number.
  • In the Route component "path" attribute , we have used "users/:userId" , ":" colon is used to make the route dynamic and the parameters can be accessed using the name "userId" as provided in the route path after colon.

Creating the Dynamic component -


import React from 'react'import {useParams} from 'react-router-dom';function UserDetails() {    const {userId} = useParams();  return (    <div>        <h1 className="text-indigo-600 m-12">User {userId}</h1>    </div>  )}export default UserDetails
  • We have used useParam hook to access the parameter values from the url.
  • as you can see we have used the exact same value "userId" for accessing the value.
  • You can check in the output, when you click on any link , the text in the UserDetail component will be changed.


You can contact me on -
Instagram -
LinkedIn -
Email - [email protected]

^^You can help me by some donation at the link below Thank you ^^
--> <--

Also check these posts as well

Original Link:

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To