'this.props.match.params.id in React.js is undefined
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);
}
Solution 1:[1]
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
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rodrigo Naranjo |
| Solution 2 | Yosi Leibman |
