How to enable select all feature in material-ui/SelectField component?

Document Link I am following the above document Link for implementing the Select-field component. I didnot find the proper document for select all in this component.

Import statement for component

import SelectField from 'material-ui/SelectField'; 

Component code:

<SelectField
    className="search_items"
    multiple={true}
    hintText="Select Item"
    value={values}
    onChange={this.handleChange} >
    {this.menuItems(values)}
 </SelectField>

menuItems Function:

menuItems(values) {
     return unique && unique.map((name) => (
        <MenuItem
            key={name}
            insetChildren={true}
            checked={values && values.indexOf(name) > -1}
            value={name}
            primaryText={name && name.concat('(').concat(sectors.filter(i => i === name).length).concat(')')}
        />
    ));
}

OnChange Function :

handleChange(event, index, values) {
    this.setState({ values })
}

How to enable select all option for all the items to be selected. Thanks in advance

Answer

Create a MenuItem above all the choices.

<SelectField
        multiple={true}
        hintText="Multiple Select"
        value={values}
        onChange={this.handleChange}
      >
          <MenuItem
            checked={this.state.open}
            value="Select all"
            onClick={this.selectAll}
            primaryText={checkedAll?"Select None":"Select all"}
          />
        {this.menuItems(values)}
      </SelectField>

Create a state checkedAll which is updated whenever the Select All item is clicked. Whenever the SelectAll MenuItem is clicked update the values to the required data(here unique) using a function.

selectAll = () => {
    if(this.state.checkedAll)
      this.setState(
        {values:[]}
      );
    else
      this.setState(
        {values:names}
      );
    this.setState({
      checkedAll:!this.state.checkedAll
    });
  }

Leave a Reply

Your email address will not be published. Required fields are marked *