Skip to content
Related Articles

Related Articles

ReactJS useParams Hook
  • Difficulty Level : Expert
  • Last Updated : 17 Mar, 2021

In our React app sometimes we want to access the parameters of the current route in this case useParams hook comes into action. The react-router-dom package has useParams hooks that let you access the parameters of the current route.

Syntax:

useParams();

Creating React Application and Installing required 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 install --save react-router-dom react-dom

Project structure:

Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :