2

Hey I have a question how can we catch the id from url

 onProductClick = item => {
    this.props.history.push(`/product/${item.id}`);
  };

How can we assign this coming id from url to variable in react

This is the place i've planned to catch the id valuer

class ProductView extends React.Component {
 componentDidMount() {
let someVar = this.props.location.pathname.split('/').pop()
console.log('router val ', someVar);}
14
  • Please clarify, what is the id you're trying to push and where it needs to come from?.. What do you mean by URL ID? Commented Mar 14, 2019 at 7:49
  • @S.Haviv Its like this localhost:3000/product/12 , In product page how can i catch the id(12) Commented Mar 14, 2019 at 7:50
  • It seems like you are using react-router, i think you should mention that in your question. So is id a query or path parameter? And exaxctly what is your question. Would you like to read the item.id again some other place in your code? Commented Mar 14, 2019 at 7:51
  • I can't see it, it's a dev server for you locally only. Commented Mar 14, 2019 at 7:51
  • @the_cheff Its like this localhost:3000/product/12 , In product page how can i catch the id(12) Commented Mar 14, 2019 at 7:52

1 Answer 1

8

It seems as if you are using react-router, the route in which you want to fetch the id should be added while declaring routes like this. > path="/product/:id" This should be done where you are mentioning your routes and routing a particular component.

Inside the routed component who will find the id in the props mostly with this value. this.props.match.params.id

This may differ depending upon the routing technique but you can log your props and fetch the value with the proper key.

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

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.