0

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.

Ramesh Raghavan
  • 119
  • 2
  • 9

1 Answers1

6

Two ways to do it:

  1. One of the two components will be the parent of the other. The state will be defined in the parent and passed as a prop to the child.
  2. The two components will be children of a third component. The state will be defined in the parent and passed to the two children as a prop.

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.

Yossi
  • 5,577
  • 7
  • 41
  • 76