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>
  • Try using ```withRouter``` react-router HOC to connect to the passed router object to the component and do a lot of other things. – Ali Torki Mar 30 '20 at 18:35
  • Have you had a chance to review the documentation for [Route](https://reacttraining.com/react-router/web/api/Route/route-props)? It looks like the following props are exposed `match, location, history` at the base level. – Alexander Staroselsky Mar 30 '20 at 18:35
  • Where is that `componentDidMount` located? Is it inside the `details` component? – Juan Marco Mar 30 '20 at 21:35

3 Answers3

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
}
Zenocode
  • 656
  • 7
  • 19
  • i get this error TypeError: Cannot read property 'params' of undefined it seems i'm getting props as an empty array – Matthew Seidel Mar 30 '20 at 18:40
  • 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 ? – Zenocode Mar 30 '20 at 18:45
0

Try

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

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

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.