Home > database >  this.props.match.params.id in React.js is undefined
this.props.match.params.id in React.js is undefined

Time:03-27

I want to get the id from the URL therefore I can use this id to get and output the user info but I can't get id from URL. I've seen useParams() but I think it is not applicable with class component. May I know if there is an alternative solution for this?

 async componentDidMount(){
    const stud_id = this.props.match.params.id;
    console.log(stud_id);
 }

see error message from console here

CodePudding user response:

The most common way of reading URL params in React is using React Router. In React Router, you get URL params with this.props.match.params like you are trying to, but you have to call your component inside a Route, like for example:

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

instead of just

<YourComponent />

So that your component receives the match prop and can access this.props.match.params.id

CodePudding user response:

If you're using

<Route path="/blah" component={()=><YourComponent someProp={someProp}>}/>

I mean, with arrow function as it child component, you have to pass the pros of the father (Route) to the child (YourComponent) like that:

<Route path="/blah" component={({match})=><YourComponent match={match} someProp={someProp}>}/>

Because you're creating a new "generation" so you have to pass the props by your self

  • Related