React checkbox if checked add value to array

15,566

Solution 1

Right now, you are assigning the workDays array to a string type.

You can use the spread operator to add values to your workDays state array. If event.target.id is already present in the workDays state you can filter it. Here is the working code snippet.

Edit reverent-franklin-ziqrn

 handleCheckboxChange = event => {
    let newArray = [...this.state.workDays, event.target.id];
    if (this.state.workDays.includes(event.target.id)) {
      newArray = newArray.filter(day => day !== event.target.id);
    } 
    this.setState({
      workDays: newArray
    });
  };

Solution 2

It's not necessary to keep an array of what boxes are checked. You can easily collect all the checked boxes when you save your data.

const checkedBoxes = document.querySelectorAll('input[type=checkbox]:checked');

If you have different groups of checkboxes, you can use a unique class to identify the group:

const checkedBoxes = document.querySelectorAll('input[class=unique-class]:checked');

Solution 3

See if this helps.

class CalenderSettingsModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      workStart: 8,
      workEnd: '',
      workDays: [],
    }
  }

  handleCheckboxChange = (event) => {
    if (event.target.checked) {
      if (!this.state.workDays.includes(event.target.value)) {
        this.setState(prevState => ({ workDays: [...prevState.workDays, event.target.value]}))
      }
    } else {
      this.setState(prevState => ({ workDays: prevState.workDays.filter(day => day !== event.target.value) }));
    }
  }


  render() {
    return (
      <React.Fragment>
        <form>
          <div>
            <h5>Select your workday(s):</h5>
            <div class="custom-control custom-checkbox" >
              {
                ["Monday", "Tuesday", /*... */].map(day => {
                  return (
                    <div class="custom-control custom-checkbox">
                      <input type="checkbox" class="custom-control-input" id={day} value={day} onChange={this.handleCheckboxChange} />
                      <label class="custom-control-label" for={day}>{day}</label>
                    </div>
                  )
                })
              }
            </div>
          </div>
        </form>
        <button >Save settings</button>
      </React.Fragment>

    );
  }
}
Share:
15,566
imkeVr
Author by

imkeVr

Updated on June 09, 2022

Comments

  • imkeVr
    imkeVr almost 2 years

    Hi this might be a very newbie question to ask but here is my question. I have check boxes that represent all the days of the week. If a day is checked I want to add it to a array so that on submit I can pass the array to back-end. I copied check box structure from bootstrap to start with. I tried to add logic to see if a box is checked and if it is checked I want to push it to my empty array in state. Also if a checkbox was checked but then unchecked I want to remove the item from the state array. So far I haven't found a way to make this all work.

    import React from 'react'
    
    class CalenderSettingsModal extends React.Component {
        constructor(props) {
            super(props);
            this.state={
                workStart: 8,
                workEnd: '',
                workDays:[],
    
            }
    
            handleCheckboxChange = (event)=> this.setState({workDays: event.target.value});
    
    
        }
    
        render() {
    
    
            return (
                <React.Fragment>
                            <form>
                                <div>
                                    <h5>Select your workday(s):</h5>
                                    <div class="custom-control custom-checkbox " >
                                        <input type="checkbox" class="custom-control-input" id="monday" value="monday"  onChange={this.handleCheckboxChange}/>
                                        <label class="custom-control-label" for="monday">Monday</label>
    
                                    </div>
                                    <div class="custom-control custom-checkbox">
                                        <input type="checkbox" class="custom-control-input" id="tuesday" value="tuesday" onChange={ this.handleCheckboxChange}/>
                                        <label class="custom-control-label" for="tuesday">Tuesday</label>
    
                                    </div>
    
                            </form>
                                <button >Save settings</button>
    
    
    
                </React.Fragment>
    
            );
        }
    }
    
    export default CalenderSettingsModal;
    
    

    With this so far I tried to accomplish assigning the value to workDays when the box is checked but isn't working and I'm not sure how I could accomplish what I want to do. Any insight would be appreciated.