useParams Hook
This hook returns an object that consists of all the parameters in URL.
Syntax:
import { useParams } from "react-router-dom";
// Inside a functional component
export default function SomeComponent(props){
const params = useParams();
}
These URL parameters are defined in the Route URL. For example,
<Route path="/profile/:userName" component={Profile} />
The colon(“:”) after “/profile/” specifies that “userName” is actually a variable or parameter that is dynamic. For example, in the url “/profile/johndoe”, “johndoe” is the value of the parameter “userName”. So, in this case, the object returned by useParams() is:
{
userName: "johndoe"
}
Example: After the login we want our user to be redirected to the “profile/userName” URL. The userName depends on the user’s given name. So, we need to set the URL path dynamically based on the user given userName. This is easy to do, we need to update the App.js file a little.
Javascript
// Filename - App.js import { Route, Switch } from "react-router-dom" ; import Home from "./components/Home" ; import ContactUs from "./components/ContactUs" ; import LogIn from "./components/LogIn" ; import AboutUs from "./components/AboutUs" ; import Profile from "./components/Profile" ; export default function App() { return ( <div className= "App" > <Switch> <Route path= "/" exact> <Home someProps={{ id: 54545454 }} /> </Route> <Route path= "/about" > <AboutUs /> </Route> <Route path= "/contact-us" > <ContactUs /> </Route> <Route path= "/log-in" > <LogIn /> </Route> { /* userName is now a variable */ } <Route path= "/profile/:userName" > <Profile /> </Route> </Switch> </div> ); } |
Javascript
// Filename - Profile.js import { useParams } from "react-router-dom" ; export default function Profile(props) { // useParams() returns an object of the parameters // defined in the url of the page // For example, the path given in the Route component // consists of an "userName" parameter // in this form ---> "/profile/:userName" const { userName } = useParams(); return ( <div> <h1> Profile of {userName}</h1> <p> This is the profile page of {userName}</p> </div> ); } |
Output: Now if you now go to the log-in page and click the login button with userName “John”, then you will be redirected to the “profile/john” page.
React-Router Hooks
React-Router is a popular React library that is heavily used for client-side routing and offers single-page routing. It provides various Component APIs( like Route, Link, Switch, etc.) that you can use in your React application to render different components based on the URL pathnames on a single page.