Reactjs - How to call the state from an input to another Class

Asked

Viewed 224 times

-1

beauty?

Well I am a layman in Reactjs, I am learning and at the same time using for work and so I have the following problem:

I have a checkbox that if it is checked a button of another component should be disabled... The question is, how do I do that? NOTE: This demand is a continuation of another company or I have more or less already done this..

File/Path: *ROOT/Climb-web/src/screens_dashboard/professional.js

<input type="checkbox" checked={ this.state.master } onChange={ this.toggleMaster } />

And I have the button on this path: *ROOT/landing_page/src/container/search.js

<Button color="info" className="text-uppercase" >Sessão gratuita</Button>

From what I saw doing some tests, I tried to import it on the way and it does not let pass of the Paste Src.

Thank you if you can help me.

Minhas pastas

1 answer

0


Luis, depending on where the checkbox and the button are, I’ll explain... If both belong to the same component you can control the disabled through a status variable. See a simple example:

<button disabled={!this.state.isActive}>Meu Botao</button>
<input type="checkbox" onChange={(event) => this.handleCheck(event)} />

constructor(props) {
    super(props);
    this.state = {
        isActive: false
    };
    this.handleCheck = this.handleCheck.bind(this);
}

handleCheck(event) {
    isActive = event.target.checked;
    this.setState({ isActive: !isActive });
}

Now if the checkbox and button are in different components you will need to adopt a means of communicating between the components to arrive at this result. A suggestion (example of use) is to use the pubsubjs but there are other ways.

Using pubsubjs you will issue a value when the checkbox is changed. At the other end (another component where the button is) you will "listen" to the values issued. When an amount is issued you can enable or disable its button:

// No componente do checkbox:
handleCheck(event) {
    isActive = event.target.checked;

    // Emite o valor do checkbox para quem estiver inscrito no canal "estadoDoBotao"
    PubSub.publish('estadoDoBotao', isActive);
}

// No outro componente, onde o botão está:
constructor(props) {
    super(props);
    this.state = { isActive: false };

    // Toda vez que um valor for emitido:
    PubSub.subscribe('estadoDoBotao', (msg, data) => {
        this.setState({ isActive: data });
    }.bind(this));
}

Browser other questions tagged

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