最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - SelectUnselect All checkbox in reactJs - Stack Overflow

programmeradmin0浏览0评论

I am trying to implement select/unselect all functionality in reactJs but couldn't make it happen.

I have made select/unselect all main header checkbox functional and the single elements can also be selected or unselected.

My work link:

import React, { Component } from 'react'
import ReactDOM from 'react-dom'

class Box extends Component{
    constructor(props){
        super(props);
        this.state = {
            allChecked: false,
            list: [
                {id:1, name: "item1", isChecked: false},
                {id:2, name: "item2", isChecked: false},
                {id:3, name: "item3", isChecked: false},
            ],
        };
    }

handleChange = (e) => {
    let list =  this.state.list;
    let allChecked = this.state.allChecked;
    if(e.target.value === "checkAll"){
        list.forEach(item => {
            item.isChecked = e.target.checked;
            allChecked = e.target.checked;
        });
    }
    else{
        list.find( item => item.name === e.target.name).isChecked = e.target.checked;
    }
    this.setState({list:list, allChecked: allChecked});
}

renderList = () => {
    return this.state.list.map(item =>
        <div>
            <input key={item.id} type="checkbox" name={item.name} value={item.name} checked={item.isChecked} onChange={this.handleChange} />
            <label>{item.name}</label>
        </div>
    )
}
render(){
    return(
        <div>
            <input type="checkbox" 
            value="checkAll" 
            checked={this.state.allChecked} 
            onChange={this.handleChange} />Check all
            <br/>
            {this.renderList()}
        </div>
    );
  }
}

ReactDOM.render(<Box/>, document.getElementById('root'));

To be straight forward, i want this (/) type of functionality using the plain Javascript but not with the jquery for some reasons.

I am trying to implement select/unselect all functionality in reactJs but couldn't make it happen.

I have made select/unselect all main header checkbox functional and the single elements can also be selected or unselected.

My work link:

import React, { Component } from 'react'
import ReactDOM from 'react-dom'

class Box extends Component{
    constructor(props){
        super(props);
        this.state = {
            allChecked: false,
            list: [
                {id:1, name: "item1", isChecked: false},
                {id:2, name: "item2", isChecked: false},
                {id:3, name: "item3", isChecked: false},
            ],
        };
    }

handleChange = (e) => {
    let list =  this.state.list;
    let allChecked = this.state.allChecked;
    if(e.target.value === "checkAll"){
        list.forEach(item => {
            item.isChecked = e.target.checked;
            allChecked = e.target.checked;
        });
    }
    else{
        list.find( item => item.name === e.target.name).isChecked = e.target.checked;
    }
    this.setState({list:list, allChecked: allChecked});
}

renderList = () => {
    return this.state.list.map(item =>
        <div>
            <input key={item.id} type="checkbox" name={item.name} value={item.name} checked={item.isChecked} onChange={this.handleChange} />
            <label>{item.name}</label>
        </div>
    )
}
render(){
    return(
        <div>
            <input type="checkbox" 
            value="checkAll" 
            checked={this.state.allChecked} 
            onChange={this.handleChange} />Check all
            <br/>
            {this.renderList()}
        </div>
    );
  }
}

ReactDOM.render(<Box/>, document.getElementById('root'));

To be straight forward, i want this (https://jsfiddle/52uny55w/) type of functionality using the plain Javascript but not with the jquery for some reasons.

Share Improve this question asked Feb 6, 2019 at 3:09 TastyTasty 511 gold badge1 silver badge8 bronze badges 4
  • I try your code, all work. Where is the problems ? – Wicak Commented Feb 6, 2019 at 3:48
  • @Wicak i want that CheckAll checkbox also to be checked, when i check all those items and want that CheckAll checkbox also to be un-checked when i uncheck if i uncheck one of the items. – Tasty Commented Feb 6, 2019 at 3:54
  • That code was missing in Codesandbox, I just recreated the same for reference. codesandbox.io/s/frosty-curie-75u6d?file=/src/App.js:395-833 – sajin tm Commented Aug 17, 2020 at 15:12
  • does anyone have a working example with buttons? – jonnie Commented May 31, 2021 at 7:57
Add a ment  | 

1 Answer 1

Reset to default 4

I have solved the problem at https://codesandbox.io/s/vvxpny4xq3

  handleChange = e => {
    let itemName = e.target.name;
    let checked = e.target.checked;
    this.setState(prevState => {
      let { list, allChecked } = prevState;
      if (itemName === "checkAll") {
        allChecked = checked;
        list = list.map(item => ({ ...item, isChecked: checked }));
      } else {
        list = list.map(item =>
          item.name === itemName ? { ...item, isChecked: checked } : item
        );
        allChecked = list.every(item => item.isChecked);
      }
      return { list, allChecked };
    });
  };

A few things to note.

1) I have updated the checkAll button to have a name property to ensure consistency

2) If modifying the existing state, use the new functional syntax

3) Destructure the objects and do not mutate them in place if possible. You could use map instead of forEach and use spread operator to modify the object without mutating.

发布评论

评论列表(0)

  1. 暂无评论