Friday, January 10, 2025
Google search engine
HomeLanguagesReactJS useParams Hook

ReactJS useParams Hook

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.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments