Global State using reactjs

0

I'm starting in the reactjs and I need to do a global state to hide / show a div but the click that hides this in another file that contains another state, how do I make it global?

    
asked by anonymous 22.03.2018 / 15:10

1 answer

1

In pure React you pass the information from parent to child via props . Then your variable that maintains the state of the div must be defined in an outer container component that contains both the component that includes the div and others.

For example:

class ComponenteContainer extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      mostrarDiv: false,
    };

    this.onToggleDiv = this.onToggleDiv.bind(this);
  }

  onToggleDiv() {
    this.setState({ mostrarDiv: !this.state.mostrarDiv });
  }

  render() {
    <div>
      <ComponenteDaDiv mostrarDiv={this.state.mostrarDiv} onToggleDiv={this.onToggleDiv}>

      <OutroComponente>
    </div>
}

The above example controls the ComponenteContainer div, which includes the state with the mostrarDiv property and the method to show / hide the div, onToggleDiv() . Note that both are passed as props ComponenteDaDiv .

If you really want a global status, I recommend Redux. But if you do not want to use Redux , you'll have to do something like a Higher-Order Component that injects the global state (a mere object ) as props in your component.

    
22.03.2018 / 23:37