Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
91
rated 0 times [  95] [ 4]  / answers: 1 / hits: 63343  / 5 Years ago, wed, january 9, 2019, 12:00:00

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!


More From » reactjs

 Answers
5

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.


[#52800] Saturday, January 5, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
deanna

Total Points: 84
Total Questions: 86
Total Answers: 107

Location: Cyprus
Member since Wed, Dec 8, 2021
3 Years ago
;