Vineet
Vineet

Reputation: 783

Option from Autocomplete aren't getting removed in React MaterialUI

I am beginner in ReactJS and currently working with Material UI Autocomplete component. I have a data object with keys as table name and columns as their value; an array of objects called columnData(is populated from values of data) with field, ifSelected as its attributes, and field attribute used to set the option label of Autocomplete(which are rendered as Chip). When an option is selected in Autocomplete dropdown then corresponding ifSelected attribute is set to true. However, problem comes when columnData object changes when a user selects different table name from data object and its corresponding value is assigned to columnData, in which previously selected option label isn't getting removed even when ifSelected attribute of all the option is false.

I went through material-ui docs here and tried fixing it using getOptionSelected prop but faced issue with deletion of chips(i.e options) with that.

Following is my code:-

import React, { Component } from "react";
import { Chip, TextField } from "@material-ui/core";
import Autocomplete from "@material-ui/lab/Autocomplete";

export default class MultiSelect extends Component {
  state = {
    table: "",
    tableData: [],
    data: {
      table1: ["col1", "col2", "col3", "col4", "col5"],
      table2: ["cola", "colb", "colc", "cold", "cole"]
    },
    columnData: []
  };

  handleTableChange = (event, value) => {
    console.log("Table change value is ", value);
    if (this.state.data[value]) {
      let columnData = this.state.data[value].map((column) => ({
        field: column,
        ifSelected: false
      }));
      console.log("Table change value is ", columnData);
      this.setState({ table: value, columnData });
    }
  };

  handleColumnChange = (columns) => {
    let data = this.state.columnData;

    if (data && columns) {
      data.forEach((column) => (column.ifSelected = false));
      console.log("Columns are ", columns);
      for (let column of columns) {
        let index = data.findIndex((item) => item.field === column.field);
        console.log("index is ", index);
        if (index !== -1) data[index].ifSelected = true;
      }
      this.setState({ columnData: data });
    }
  };

  componentDidMount() {
    let tableData = Object.keys(this.state.data);
    this.setState({ tableData });
    this.handleTableChange("table1");
  }

  render() {
    return (
      <>
        <Autocomplete
          id="table"
          options={this.state.tableData}
          getOptionLabel={(option) => option}
          renderInput={(params) => (
            <TextField {...params} variant="outlined" margin="normal" />
          )}
          value={this.state.table}
          onChange={this.handleTableChange}
        />
        <Autocomplete
          disabled={!this.state.table}
          style={{ marginTop: "1rem" }}
          multiple
          disableCloseOnSelect
          limitTags={3}
          options={this.state.columnData}
          getOptionLabel={(option) => option.field}
          renderInput={(params) => (
            <TextField
              style={{ fontWeight: "700" }}
              {...params}
              variant="outlined"
            />
          )}
          renderTags={(value, getTagProps) =>
            value.map((option, index) => (
              <Chip
                variant="outlined"
                key={option}
                label={option.field}
                {...getTagProps({ index })}
              />
            ))
          }
          onChange={(event, newValues) => this.handleColumnChange(newValues)}
        />
      </>
    );
  }
}

Would appreciate any hint. I have added demo here

Upvotes: 1

Views: 308

Answers (1)

Arun Kumar Mohan
Arun Kumar Mohan

Reputation: 11905

You can fix the issue by passing the value prop to select the columns with ifSelected set to true.

<Autocomplete
  value={this.state.columnData.filter((column) => column.ifSelected)}
  // other props
/>

CodeSandbox

Upvotes: 2

Related Questions