Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the useParams hook in react

I am learning useParams hook in react. I have a url like this and need to be able to extract the letter 9 from it.

    http://localhost:3010/9/solution

How can I go about this ?

like image 202
Baba Avatar asked Apr 02 '20 18:04

Baba


People also ask

How do I use useParams in ReactJS?

Step 1: Create a React application using the following command. Step 2: After creating your project folder i.e. useparams_react, move to it using the following command. Step 3: After creating the ReactJS application, Install the react-router-dom and react-dom packages using the following command.

Why we use useParams hook?

The useParams hook returns an object of key/value pairs of the dynamic params from the current URL that were matched by the <Route path> . Child routes inherit all params from their parent routes.

How do you access the URL path using useParams hook in React JS?

import React from 'react' import './App. Notice that we have passed the products object as a prop to the ProductsPage component so that we can display it there. In the Product component, we will use the useparams hook to extract the id from the url for each product. import React from 'react' import './App.

How do I use useParams ID?

Use the useParams() hook to get the ID from a URL in React, e.g. const params = useParams() . The useParams hook returns an object of key-value pairs of the dynamic params from the current URL that were matched by the Route path.


1 Answers

I'm assuming you're using react router, if you define a route like this for example:

<Route path="/:id/about">
 <About />
</Route>

Notice that you define the path with this :id notation, that means that the id will be the param in this specific case. Then you create a Link component

<Link to="/2/about">About</Link>

And in your component that in this example is the about component you can use the hook like this:

function About() {
 const { id } = useParams();
 return (
  <div>
   <h2>Now showing post {id}</h2>
  </div>
 );
}

I have this code sandbox if you want to check the result https://codesandbox.io/s/react-router-basic-nv8pn

like image 50
jean182 Avatar answered Oct 02 '22 02:10

jean182