State Global using reactjs

Asked

Viewed 640 times

0

I’m starting at reactjs and need to do a global state to hide/show a div but click this on another file containing another state, as I do to let it global?

2 answers

1


In pure React you pass the information from father to son via props. Then its variable that keeps the state of the div must be defined in an outside 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, which includes the state with the property mostrarDiv and the method to show/hide the div, onToggleDiv(). Note that both are passed as pro props ComponenteDaDiv.

If Voce really wants a global state, I recommend Redux. But if you don’t want to use Redux, you will have to do something like a Higher-Order Component that injects the global state (a mere object) as props into its component.

-3

Search Context API, is simpler than Redux (in my opinion) and will solve your problem. Basically you create a context (in your case the context will be in the component that is clicked), and you export this state to your entire application.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.