1

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>

4
  • blue and yellow are selected, where is the problem ? you want to change them recheck and check Nov 30, 2019 at 14:24
  • You probably want to assign onChange for every input and change checkedColors according to the new selection. This, in turn, will reflect in the updated checked state of the inputs. See reactjs.org/docs/forms.html#controlled-components for more details. Nov 30, 2019 at 14:30
  • @RenaldoBalaj yes i can see it, but i need to check more colors if i want Nov 30, 2019 at 14:33
  • i gave a working demo at the answer, comment there Nov 30, 2019 at 14:35

2 Answers 2

1

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

1

You can achieve this by assigning a true boolean value to the checked attribute.

Sample code below:

checked={ yourCondition ? true : false }

If your condition is matched, the checkbox will be checked.

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.