Reputation: 526
I am setting a state into child component on event perform and want to sent this to Parent component. I searched for this on SO. But still didn't found any way to do this.
Let say i have a parent component Home, and have child component User. I am performing some event in User component, and at that time, i want to pass data to Home component. How can i do this?
Below is my code:
/* Parent component */
import React, { Component } from 'react';
import User from './user';
class Home extends React.Component{
constructor(props){
super(props)
this.state = {
isReportSent: false
}
}
render(){
<Switch>
<Route exact path="/" component={User}/>
</Switch>
}
}
/* child component */
class User extends React.Component{
constructor(props){
super(props)
}
render(){
}
}
Note: My parent component is Routing component, in which i am routing my child component on particular path. So can't pass any function to child component.
Upvotes: 1
Views: 128
Reputation: 195962
You can actually pass a method, you just need to use the render prop
<Switch>
<Route exact path="/" render={(props)=><User {...props} someMethod={someMethod} />}/>
</Switch>
Upvotes: 0
Reputation: 281616
You can make use of render
props in Routes to pass callback method to child which you can then use to update the parent
import React, { Component } from 'react';
import User from './user';
class Home extends React.Component{
constructor(props){
super(props)
this.state = {
isReportSent: false
}
}
performUpdate = () => {
}
render(){
<Switch>
<Route exact path="/" render={(props) => <User {...props} performUpdate={this.performUpdate}/>}/>
</Switch>
}
}
/* child component */
class User extends React.Component{
constructor(props){
super(props)
}
handleClick=() => {
this.props.performUpdate(); //call to inform parent about change
}
render(){
}
}
Upvotes: 2