3

I have my toggle for checkbox in my application. It's not working.

I have tried using onChange function but it's not working.


Checkbox

<input 
    id="switchCheckboxInputAssert" 
    className="switch-checkbox-input" 
    type="checkbox" 
    checked={this.state.option.assert == 1 ? true : false} 
    value={this.state.option.assert} 
    onChange={this.assertChange}
    disabled={!this.props.canBeSolution} 
/>

onChange function

assertChange = () =>
    this.setState({
        option: { ...this.state.option, assert: !this.state.option.assert }
    })

How can I toggle my checkbox properly?

1
  • Your code is working fine. Just check what you are getting as this.props.canBeSolution true / false. Commented Sep 17, 2019 at 5:31

2 Answers 2

3

I think you're mixing up controlled and uncontrolled components/elements. If you want to allow the checkbox to toggle you should rather pass the value as the default value instead of the value, and pass the checked value to your callback

<input
  id="switchCheckboxInputAssert"
  className="switch-checkbox-input"
  type="checkbox"
  // pass state value as default checked value
  defaultChecked={this.state.option.assert}
  // pass checked value to callback
  onChange={evt => this.assertChange(evt.target.checked)}
  disabled={!this.props.canBeSolution}
/>

Edit intelligent-mayer-ve1i9

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

Comments

0

You don't need to use value attribute, just use checked attribute without any logic as you are already taking care of login inside assertChange function for checkbox in react.

<input
  id="switchCheckboxInputAssert"
  className="switch-checkbox-input"
  type="checkbox"
  checked={this.state.option.assert}
  onChange={this.assertChange}
   />

working demo

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
state = {
  option: {
    'something': 'new something',
    assert: true
  }
}
  assertChange = () => {
    this.setState({
      option: { ...this.state.option, assert: !this.state.option.assert }
    })
  }
  render() {
    console.log(this.state.option)
    return (
      <div className="App">
        <input
          id="switchCheckboxInputAssert"
          className="switch-checkbox-input"
          type="checkbox"
          checked={this.state.option.assert}
          onChange={this.assertChange}
           />
        <h2>Start editing to see some magic happen!</h2>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Hope that helps!!!

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.