Reputation: 149
I have two js files, one is app.js and the other one is foo.js. I want to access the state of app.js in foo.js.
App.js
class App extends React.Component {
constructor(props) {
super(props);
this.state = {test:" None "};
}
function onChange(event) {
this.setState({
test: event.target.value,
});
}
render() {
return(
<select onChange={this.onChange}>
<option value="India">India<option>
<option value="Australia">Australia<option>
</select>
);
}
}
export default App;
now i want to access the above state (test) in foo.js file.
Foo.js
class Foo extends React.Component {
render() {
/* Some magic happens */
return(<h1>{this.props.test}</h1>);
}
}
Am new to reactjs. How can i do it? Thanks for help in advance.
Upvotes: 1
Views: 6214
Reputation: 6027
Two ways to do it:
If you need to modify the state in one of the children components, you will need to pass a callback function from the parent to the child, so that the child calls it to perform a change.
Upvotes: 7