Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing parent state in child in React

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>         )     } } 
like image 435
GluePear Avatar asked Jan 24 '17 10:01

GluePear


People also ask

How do you access the state in a parent from child react?

In React we can access the child's state using Refs. we will assign a Refs for the child component in the parent component. then using Refs we can access the child's state. Creating Refs Refs are created using React.

How do you access the state in child components?

You may access the child state by passing a callback to the child component. Now if you click the button in the child component, you will execute the function passed from the parent and have access to the child component's state variables.


2 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>;  })} 
like image 195
pwolaq Avatar answered Sep 20 '22 22:09

pwolaq


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>;      }) } 
like image 39
Mayank Shukla Avatar answered Sep 20 '22 22:09

Mayank Shukla