Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access parent component state in child component?

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 ?

like image 226
Mukund Kumar Avatar asked Jan 29 '26 02:01

Mukund Kumar


2 Answers

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:

  1. Use a state management solution like 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.
  2. Use Contexts. From the docs: In some cases, you want to pass data through the component tree without having to pass the props down manually at every level. You can do this directly in React with the powerful "context" API. If you want to avoid using Redux or Mobx or any state management this may be the way to go.
like image 178
André Pena Avatar answered Jan 31 '26 19:01

André Pena


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

like image 37
Poulima Biswas Avatar answered Jan 31 '26 21:01

Poulima Biswas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!