1
votes

I have the below code to display switch state inside a table in material ui. But I am stuck on how to add onChange behaviour to the individual row switchs. Any advice on the same?

    <Paper className={classes.root}>
                    <Table className={classes.table}>
                        <TableHead>
                        <TableRow >
                            <TableCell></TableCell>
                            <TableCell  className={classes.head} >Accept Orders</TableCell>
                            <TableCell   className={classes.head} >Process Send Queue</TableCell>
                        </TableRow>
                        </TableHead>
                        <TableBody className={classes.body}>
                        {array.map(row => {
                            return (
                            <TableRow key={row.cryptoCode} className={classes.row}>
                                <TableCell component="th" scope="row">{row.cryptoCode}</TableCell>
                                <TableCell>        
                                    <Switch
                                        checked={row.acceptOrders}
                                        onChange={this.handleChange}
                                        // value="checkedA"
                                     />
                                </TableCell>
                                <TableCell>                               
                                    <Switch
                                        checked={row.processSendQueue}
                                        onChange={this.handleChange}
                                        // value="checkedB"
                                     />
                                </TableCell>
                            </TableRow>
                            );
                        })}
                        </TableBody>
                    </Table>
 </Paper>
1

1 Answers

0
votes

In your onChange method you can pass an index as argument to the callback function. On the callback function you edit the row object and setState. Something like:

   handleChange: function(rowIndex){
      var array = this.state.array;
      array[rowIndex][isChecked] = !array[rowIndex][isChecked];
      this.setState({array: array});
   }

   render: function(){
      return(
          ...
          <Switch
             checked={row.acceptOrders}
             onChange={this.handleChange.bind(this,index)}
             value={row.isChecked}
          /> 
          ... 
      );
   }