Accessing parent state in child in React
Matthew Barrera
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> ) }
} 1 3 Answers
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>;
})} 5 Another way of doing this is:
<Route path="/docs" component={() => <Docs docs={this.state.docs}/>}>If you need to pass children:
<Route path="/" component={(props) => <Docs docs={this.state.docs}>{props.children}</Docs>}>If you are doing it like this, then you can access your props values directly by this.props.docs in Child Component:
{ this.props.docs.map((study, key)=> { return <p key={key}>Random text here</p>; })
} Another way of doing this will be
<Route path='/' render={ routeProps => <Home {...routeProps} docs={this.state.docs} /> } />While in the child component you can access docs using
this.props.docsHope it helps!