1

Using react-bootstrap, I want a checkbox on my form to be checked when my 'inactive' value is true; and not when it's false. So I set the checked attribute to this pretty straightforward line:

checked={inactive}

But I get this error when I click the checkbox: "Warning: Received the string false for the boolean attribute checked. The browser will interpret it as a truthy value. Did you mean checked={false}?"

Here's the relevant code:

render() {
  const {
    inactive,
    ...
  } = this.state;

  return (
    <Form.Group as={Row}>
      <Form.Label>Inactive<Form.Label>
      <Col>
        <Form.Check
          type="checkbox"
          checked={this.state.inactive}
          onChange={() => {
            if (inactive === 'false') {
              this.setState({ inactive: 'true' });
            } else {
              this.setState({ inactive: 'false' });
            }
          }}
        />
      </Col>
    </Form.Group>
    );
  } 
}

So then I changed the checked attribute to the following. But in this case, the the value does not get set correctly when false:

...
      checked={inactive === 'true'}
...

2 Answers 2

2

if your state is this:

state={
inactive:false,
....
}

Remove this object de-structuring:

const {
    inactive,
    ...
  } = this.state;

and make changes as this

 <Form.Check
          type="checkbox"
          checked={this.state.inactive}
          onChange={() => {
            this.setState({ inactive: !this.state.inactive });
          }}
        />

I hope this helps!

See this sandbox

Sign up to request clarification or add additional context in comments.

Comments

0

you state needs to be :

this.state = {
          inactive: false
}

and remove this object destructuring:

const {
inactive,
...
} = this.state;

Another optimization to avoid if-else...

onChange={()=>this.setState({
    inactive: !this.state.invactive
)}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.