I have this code in my parent component:
<Route path='/champions/:id' render={(props) => <ChampionDetails {...props} match={this.handleMatch}/>}/>
where the match prop will be a function that retrieves data from the child component (ChampionDetails). A snippet of my ChampionDetails (child) component:
import React, { Component } from 'react';
class ChampionDetails extends Component {
state = {
champId:this.props.match.params.id,
champData:null,
match:false
}
componentDidMount(){
console.log('ChampionDet mounted')
this.handleChampInfo();
console.log(this.props.match)
}
componentDidUpdate(){
console.log('ChampionDet updated')
}
handleChampInfo=()=>{
let champData = [];
let id = this.state.champId
console.log(id)
fetch('/api/getChampion?id='+id)
.then(data=> { return data.json() })
.then(json=> {
console.log(json.data);
champData.push(json.data);
this.setState({
champData:json.data,
match:true
})
this.props.match(true)
// this.props.history.push('/champions/'+id)
})
.catch(err=>{
console.log(err)
})
}
render(){
return(
<div>
<p>{this.state.champId}</p>
{this.state.champData===null ? null:<p>{this.state.champData.roles}</p>}
</div>
)
}
}
export default ChampionDetails;
The problem here is that if I have the match={} in my parent's route, then this.props.match.params.id will become undefined. If I remove match={} then I can retrieve this.props.match.params.id
I would like to know if its possible to be able to pass other props while still have access to this.props.match.params.id in my case.
Any help will be much appreciated!
Just create constructor i.e constructor(props) {} and inside it declare the id as a state variable to the class. Pass the value of match.params.id to the id by using id: this.props.match.params.id . Now u can access the state variable anywhere in your code and hope it solves your problem. Save this answer.
The exact prop is used to define if there is an exactly the requested path.
If you're using react-router
version >=4
, you should be able to access the router params at any component inside the router via withRouter
HOC. For instance:
import { withRouter } from 'react-router-dom';
...
export withRouter(ChampionDetails);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With