Matthew Seidel
Matthew Seidel

Reputation: 11

get id from url params react.js

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>

Upvotes: 0

Views: 4589

Answers (3)

adamicska
adamicska

Reputation: 1

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.

Upvotes: 0

Scott Fraser
Scott Fraser

Reputation: 31

Try

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

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

Upvotes: 0

Zenocode
Zenocode

Reputation: 702

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
}

Upvotes: 4

Related Questions