Accessing parent state in child in React

GluePear picture GluePear · Jan 24, 2017 · Viewed 31.6k times · Source

I have (e.g.) two components in React. The first, app.js, is the root component. It imports some JSON data and puts it in its state. This works fine (I can see it in the React devtools).

import data from '../data/docs.json';

class App extends Component {
  constructor() {
    super();
    this.state = {
      docs: {}
    };
  }
  componentWillMount() {
    this.setState({
      docs: data
    });
  }
  render() {
    return (
      <Router history={hashHistory}>
        <Route path="/" component={Wrapper}>
          <IndexRoute component={Home} />
          <Route path="/home" component={Home} />
          <Route path="/docs" component={Docs} />
        </Route>
      </Router>
    );
  }
}

The second, docs.js, is meant to show this JSON data. To do that it needs to access the state of app.js. At the moment it errors, and I know why (this does not include app.js). But how then can I pass the state from app.js to docs.js?

class Docs extends React.Component {
    render() {
        return(
            <div>
                {this.state.docs.map(function(study, key) { 
                    return <p>Random text here</p>; 
                })}
            </div>
        )
    }
}

Answer

pwolaq picture pwolaq · Jan 24, 2017

The proper way of doing this would be by passing state as props to Docs component.

However, because you are using React Router it can be accessed in a bit different way: this.props.route.param instead of default this.props.param

So your code should look more or less like this:

<Route path="/docs" component={Docs} docs={this.state.docs} />

and

{this.props.route.docs.map(function(study, key) { 
    return <p>Random text here</p>; 
})}