0

i'm triyng to get the id from url params i'm using in react.js. This is my code

componentDidMount() {
    let {id} = this.props.params
}

but i get undefined, i console loged params and i get an empty array

how can i get the param?

this is the router code

<BrowserRouter>
    <Navbar />
      <Switch>
        <Route exact path="/" component={home} ></Route>
        <Route exacth path="/details/:id" component={details} />
      </Switch>
</BrowserRouter>
3
  • Try using withRouter react-router HOC to connect to the passed router object to the component and do a lot of other things. Commented Mar 30, 2020 at 18:35
  • Have you had a chance to review the documentation for Route? It looks like the following props are exposed match, location, history at the base level. Commented Mar 30, 2020 at 18:35
  • Where is that componentDidMount located? Is it inside the details component? Commented Mar 30, 2020 at 21:35

3 Answers 3

4

According to https://stackoverflow.com/a/45069909/6809926, you will be able to access your id using this.props.match.params instead of this.props.params:

componentDidMount() {
    let {id} = this.props.match.params
}
Sign up to request clarification or add additional context in comments.

2 Comments

i get this error TypeError: Cannot read property 'params' of undefined it seems i'm getting props as an empty array
In your Route you write : exacth instead of exact could be something ? Also did you try to just print this.props to see its content ?
0

Try

componentDidMount () {
    const { id } = this.props.match.params
}

see https://tylermcginnis.com/react-router-url-parameters/

Comments

0
componentDidMount () {
        const { id } = this.props.match.params.id
    }

console.log(id) brings back the id alright in my case. Without the .id, I get an object.

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.