mercredi 25 mai 2022

How to Handle Multiple Checkboxes in typescript

I am trying to handle multiple checkboxes as follows:

sendFileNameToBackEnd = (filename: string[]) => {
    console.log(filename)
    this.vizsualizaForFileName(filename)
  }

render() {
  const handleChange = (checked: boolean, event: React.FormEvent<HTMLInputElement>) => {
      let listoffilename : Array<string> = []
      const target = event.currentTarget;
      const name = target.name;
      if(checked && name !== '')
        {
          listoffilename.push(name)
          this.setState({
            listoffilename1: listoffilename
          });
        }
        console.log(this.state.listoffilename1)
 };
 return (
 <DataList aria-label="Checkbox and action data list example" isCompact >
   { this.state.fileListData ?
     this.state.fileListData.map((fd) => 
     <DataListItem aria-labelledby="check-action-item1">
       <DataListItemRow>
         <DataListCheck 
           id="controlled-check"
           aria-labelledby="check-action-item" 
           isChecked={isChecked1}
           onChange={handleChange} 
           name={fd}/>
         <DataListItemCells
           dataListCells={[
            <DataListCell key="primary content">
              <span id="check-action-item1">{fd ? fd : "Loading..."}</span>
            </DataListCell>
           ]}
         />
       </DataListItemRow>
     </DataListItem>
     ): 
     <>
       <EmptyState>
        <Title headingLevel="h4" size="lg">Empty state</Title>
       </EmptyState>
     </>
  }
 </DataList>
<Button variant="primary" onClick={ () => {this.sendFileNameToBackEnd(this.state.listoffilename1)}}>Visualize</Button>
 );
}

In the above code, when I select any one checkbox, I can get its value, but when I choose multiple checkboxes after that, I am also getting only one value in an array.

In 'this.state.fileListData' I have n number of data and I am displaying a checkbox using a map and one button called 'Visualize'. When we select some of the values from the checkbox and click on the 'Visualize' button then I want to send all selected values to the backend for another operation.

When I select multiple checkboxes then it only sends one value in it not all selected values.

Guide me if I am doing something wrong.




Aucun commentaire:

Enregistrer un commentaire