I am using react-router(v3) for routing purpose in my app. I have some nested route and want to access parent component state in child component.
Route:
<Route component={Main}>
<Route path="home" component={Home} />
</Route>
Main Component(parent):
export default class Main extends Component {
constructor(prop){
super(prop);
this.state = {
user : {}
}
}
render(){
return (
<div>
Main component
</div>
)
}
}
Home Component(child):
export default class Home extends Component {
constructor(prop){
super(prop);
}
render(){
return (
<div>
Main component
want to access user data here. how to access user from parent component?
</div>
)
}
}
In Home component i want to access user data, that is in parent component Main. Is there any way to access parent component state in child component ?
Your problem is that you can't just pass user as props to Home because App is not direcly rendering Home. You're doing that through React-Router.
You got 2 approaches here:
Redux and connect() both Main and Home to the user in store. This way, user is not part of Main state, but part of the app store and can be accessed from other components. This is the most sophisticated / extensible solution.send state of parent component as props to child component. within Parent component fetch child like this...
<Home user={this.state.user} />
Access user in child by this.props.user
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