How to get the checked data using reactjs

Viewed 48

my Objective is to remove the list of selected objects, if i checkAll then it should show empty list or if i select one item from the Table then it should remove the selected item from the list. But i couldn't able to get the checked object.

Json look like :

const data =[
{
id: "12shgdfyd78"
name: "ABC"
isSelected: true
phone: "1234569874"
},
{
id: "18htfdwcfe78"
name: "EFG"
isSelected: true
phone: "9587463215"
}
]

if i select the first one then the whole object need to appear, But could not able to get it.

If have tried in this way:

handleCheck = (e) => {
let value = e.target.name //will get the phone number
let checked = e.target.checked;
let checkedList = this.props.data.map((item)=> item.phone == value? Object.assign(item,{isSelected: checked,}): item
this.setState({checkItems: checkedList})
}

handleSubmit = () => {
const data = this.state.checkItems.filter(item=>item.isSelected).map(item=>item.phone)
}

But didn't get the object.

Can anyone please help me in this query?

3 Answers

this is how I would go about it

class CheckBox extends React.Component {
  constructor(props){
  }

  render() {
    <input type="checkbox" onClick={e=>this.props.handleCheck(this.props.object)}   name={this.props.object.name} value={object}>
}
}

 
class CheckBoxGroup extends React.Component {
   constructor(){
   
    this.handleClick = this.handleClick.bind(this);
    this.state={
          data:[
         {
            id: "12shgdfyd78"
            name: "ABC"
            isSelected: true
            phone: "1234569874"
         },
         {
            id: "18htfdwcfe78"
            name: "EFG"
            isSelected: true
             phone: "9587463215"
         }
        ],
        selectedObject:null,
       } 
  }


   handleCheck = (object) => {
   console.log(object)
   }

   render(){
 return this.data.map((d,i)=><CheckBox key={i} handleCheck={this.handleCheck }  index={i} object={d} />)
}

  

}

You can make use array.map and array.filter function to achieve your use case, please checkout the codesandbox example i made here.

As per my understanding you have Select All checkbox and other checkboxes based on data in your state. If one of them is unchecked then it should not display and select all is selected then it should bring back all. It can be achieved using filter and map functions of array. Check below example in below link it is somewhat near that you are looking for:

Select All Demo

Related