Search code examples
sasshovercheckeddisabled-inputbem

checkbox defalut checked and also disabled in React.js not working


Hi im trying to make a switch button (checkbox) with default checked and also disabled in react. but somehow if I only put checked={true} it will be checked but the moment i add disabled="disabled", the switch button is unchecked and disabled (even if there is checked attribute). Could anyone please advise? thank you

 <label htmlFor="disabled-on" className="switch__label">
            <input
                type="checkbox"
                name="disabled-on"
                id="disabled-on"
                checked={true}
                disabled="disabled"  /* if added disabled it's not working with checked" */
                className="switch__input switch__input--disabled-on"
            />

Solution

  • It is probably something wrong in your code somewhere else, please check this code - all looks fine.

    class TodoApp extends React.Component {
      constructor(props) {
        super(props)
      }
      
      render() {
        return (
          <div>
            <ul>
              <li>
              <label htmlFor="disabled-on" className="switch__label">
                 custom checkbox 1
                  <input
                      type="checkbox"
                      name="disabled-on"
                      id="disabled-on"
                      checked={true}
                      disabled="disabled"
                      className="switch__input switch__input--disabled-on"
                  />
              </label>
              </li><li>
              <label htmlFor="disabled-on" className="switch__label">
                 custom checkbox 2
                  <input
                      type="checkbox"
                      name="disabled-off"
                      id="disabled-off"
                      checked={true}
                      className="switch__input switch__input--disabled-on"
                  />
              </label>
              </li>
            </ul>
          </div>
        )
      }
    }
    
    ReactDOM.render(<TodoApp />, document.querySelector("#app"))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <div id="app"></div>