jeudi 20 août 2020

How to fixe setState() gives the opposite value of checkbox?

This is my class component:

import React from 'react';

import { Jumbotron, Container, Label } from 'reactstrap';

import './Css.css';

class Settings extends React.Component {

  state = {
    isChecked: false,
  }

  isCheck(e) {
    this.setState({
      isChecked: e.target.checked
    })
    console.log(e.target.checked)
    console.log(this.state.isChecked)
  }


  render() {
    return (
      <div className="margin">
        <Jumbotron fluid>
          <Container fluid>
            <h1 className="display-3">Settings</h1>

            <div className="groupbox">
              <Label className="lead">This is a checkbox</Label>
              <input class="apple-switch" type="checkbox" onChange={e => this.isCheck(e)} />
            </div>

          </Container>
        </Jumbotron>
      </div>
    );
  }
}

export default Settings;

The problem that I have is that the values that I get in the console are inversed.

So when the checkbox is unchecked e.target.checked is false but this.state.isChecked is true, and when the checkbox is checked e.target.checked is true and this.state.isChecked is false.

I don't know why I'm facing this issue.

  • Is there anything that I did wrong?

I tried also to store the e.target.checked to a const checked and then pass it to the setState() but it gives me the same thing.

Any help is appreciated.




Aucun commentaire:

Enregistrer un commentaire