1
votes

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 ?

2
the proper way of doing this would be by passing state as props to Home component or In your parent, you can create a function like addUser which will do the required setState and then pass that function as props to the child component.Nicholas

2 Answers

11
votes

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.
0
votes

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