6

I have a url like this:

http://localhost:3000/1

The "1" is the user id as parameter, how can I get it in react js?

5
  • are you using react-router ? Commented Jan 2, 2020 at 14:11
  • are you using react router or react router dom as a package for routing in react app ? Commented Jan 2, 2020 at 14:43
  • I have added a working example, is this what you are looking for, in the codesandox url you can type product/2, so it will display whatever id you have typed in the codesandbox url codesandbox.io/s/59564616-so-react-routing-getting-params-e1flt Commented Jan 2, 2020 at 14:49
  • this.props.match.params.parm_name Commented Jan 2, 2020 at 15:00
  • @DILEEPTHOMAS the codesandox was helpful, thnks! Commented Jan 2, 2020 at 17:39

3 Answers 3

7

If router is like this

<Route exact path="/category/:id" component={ProductList}/>

Access like this

this.props.match.params.id

for your reference URL Parameters with React Router

Sign up to request clarification or add additional context in comments.

1 Comment

It works, thks! I didn't know the Router so I had a little work
6

FWIW it's much easier now using hooks in React Router DOM v5 (link)

In Router define routes as normal:

<Route path="/users/:id" ...

And in the Component, simply deconstruct the useParams hook:

const { id } = useParams();

It's that simple!

Comments

1

==============================Using component==================

<Route path="/users/:id" component={UserPage}/> 

this.props.match.params.id

===============================Using render====================

<Route path="/users/:id" render={(props) => <UserPage {...props} />}/> 

this.props.match.params.id

For Query Parameter: https://github.com/sindresorhus/query-string

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.