Ramesh Raghavan
Ramesh Raghavan

Reputation: 149

How to use state of one component in another file in reactjs?

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

Answers (1)

Yossi
Yossi

Reputation: 6027

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.

Upvotes: 7

Related Questions