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> ) } }
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.
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.
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>; })}
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>; }) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With