samedi 30 juin 2018

How to set a max number of checked boxes

I have a list of option with a corresponding checkbox (Material-UI) And I'm trying to figure out how I Can set a max number on checked boxes (for instance, I would only want the user to be able to click three and then disable the rest) Do I do this in the state?

const styles = theme => ({
  root: {
    width: '100%',
    maxWidth: 260,
    backgroundColor: theme.palette.background.paper,
  },
});

class CheckboxList extends React.Component {
  state = {
    checked: [0],
  };

  handleToggle = value => () => {
    const { checked } = this.state;
    const currentIndex = checked.indexOf(value);
    const newChecked = [...checked];

    if (currentIndex === -1) {
      newChecked.push(value);
    } else {
      newChecked.splice(currentIndex, 1);
    }

    this.setState({
      checked: newChecked,
    });
  };

  render() {
    const { classes } = this.props;
    const toppings = ['Chicken', 'Pineapple', 'Corn', 'Olives (green)', 'Red union', 'Spinach', 'Cherry tomatoes']
    return (
      <div className={classes.root}>
        <List>
          {toppings.map(value => (
            <ListItem
              key={value}
              role={undefined}
              dense
              button
              onClick={this.handleToggle(value)}
              className={classes.listItem}
            >
              <Checkbox
                checked={this.state.checked.indexOf(value) !== -1}
                tabIndex={-1}
                disableRipple
              />
              <ListItemText primary={`NewAge ${value}`} />

            </ListItem>
          ))}
        </List>
      </div>
    );
  }
}

CheckboxList.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(CheckboxList);




Aucun commentaire:

Enregistrer un commentaire