Reputation: 105
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!
Upvotes: 9
Views: 67715
Reputation: 4561
Match prop is part of the react-router-dom
, so by making another props called match you are overwriting it.
The simplest way: just rename the match={this.handleMatch}/>}
to something else like
matchHandler={this.handleMatch}/>}
If using the name match
is essential, destruct it as const {matchHandler : match} = this.props
Upvotes: 0
Reputation: 731
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);
Upvotes: 20
Reputation: 13385
You can pass matchProps
as the props from the router, this.props
for any props from the parent and then just avoid overwriting props - your match
prop is overriding the props from the route:
<Route path='/champions/:id' render={(matchProps) =>
<ChampionDetails
{...matchProps}
{...this.props}
handleMatch={this.handleMatch}
/>
}/>
When you spread {...props}
your match
prop overrides react-router's match
.
Upvotes: 10