javascriptreactjscheckboxchecklistbox

How to precheck some checkbox in ReactJS


My code has many atributes that have to be choosed by user, he can choose 0 or all and sometimes some atributes will come checked if this user has been choose the atributes before, i've try hard to do this with reactjs but checked and defaultChecked props are confuse to me, here my code sample.

class App extends React.Component {
  state = {
    colors: [ 'red', 'black', 'green', 'blue', 'white', 'yellow' ],
    checkedColors: [ 'blue', 'yellow' ]
  }

  handleSubmit(e) {
    e.preventDefault()
    const { target } = e
    const formData = new FormData(target)
    const checkedColors = formData.getAll('colors')
    this.setState({ checkedColors })
  }
  
  render() {
  const { colors, checkedColors } = this.state
  return (
    <form onSubmit={this.handleSubmit.bind(this)}>
      <ul>
        {colors.map((color, index) => (
          <li key={index}>
            <input
              type='checkbox'
              name='colors'
              id={color}
              value={color}
              checked={checkedColors.some(chckColor => chckColor === color)}
            />
            <label htmlFor={color}>{color}</label>
           </li>
         ))}
        </ul>
        <button>submit</button>
        <span>{checkedColors.join(', ')}</span>
       </form>
     )
   }
}

ReactDOM.render(<App />, document.getElementById('root'))
<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="root"></div>


Solution

  • https://stackblitz.com/edit/react-5pdd5f You have the working demo here :)

    The checkbox needs 2 attributed: checked: which is true or false (you can set default here too)

    onChange: when someone removes the click or adds a click you must register it

    For questions comment below