ReactJS useParams Hook
React JS useParams Hook helps to access the parameters of the current route to manage the dynamic routes in the URL. The react-router-dom package has useParams hooks that let you access and use the parameters of the current route as required.
Prerequisites:
Approach:
- Define the dynamic routes for the specific components in which we want to access parameters.
- Using the useParams hook access the URL and hence the params from the URL.
- Use the Params inside the component and display it on the UI.
Syntax for useParams Hook:
useParams();
Steps to Create React Application and Installing Modules:
Step 1: Create a React application using the following command.
npx create-react-app useparams_react
Step 2: After creating your project folder i.e. useparams_react, move to it using the following command.
cd useparams_react
Step 3: After creating the ReactJS application, Install the react-router-dom and react-dom packages using the following command.
npm i --save react-router-dom@5 react-dom
Project structure:
The updated dependencies in package.json file.
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^5.3.4",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
Example: This example use useParam to access and use params inside the component from the URL.
Javascript
// Filename - App.js import React from "react" ; import { BrowserRouter as Router, Switch, Route, useParams, } from "react-router-dom" ; function BlogPost() { let { id } = useParams(); return ( <div style={{ fontSize: "50px" }}> Now showing post {id} </div> ); } function Home() { return <h3>home page </h3>; } function App() { return ( <Router> <Switch> <Route path= "/page/:id" > <BlogPost /> </Route> <Route path= "/" > <Home /> </Route> </Switch> </Router> ); } export default App; |
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output. You can see what you have passed in the URL as “: id” is displayed on the screen. In this way, you can access the parameters of the current route’s URL.
Contact Us