admin管理员组

文章数量:1332896

So I want to display selected values as <Chip /> outside of the <TextField /> in <Autoplete />. I was able to display values as state. However, I still have trouble deleting those chips, i.e. not just the display, but also change the selected prop in <Autoplete />. Does anyone have an idea?

  const [val, setVal] = useState([]);

  const valHtml = val.map((option, index) => (
    <Chip
      label={option.title}
      deleteIcon={<RemoveIcon />}
      onDelete={() => {}}
    />
  ));

  return (
    <div>
      <Autoplete
        multiple
        filterSelectedOptions
        options={top100Films}
        onChange={(e, newValue) => setVal(newValue)}
        getOptionLabel={option => option.title}
        renderTags={() => {}}
        renderInput={params => (
          <TextField
            {...params}
            variant="standard"
            placeholder="Favorites"
            margin="normal"
            fullWidth
          />
        )}
      />
      <div className="selectedTags">{valHtml}</div>
    </div>
  );
}

Complete code here

So I want to display selected values as <Chip /> outside of the <TextField /> in <Autoplete />. I was able to display values as state. However, I still have trouble deleting those chips, i.e. not just the display, but also change the selected prop in <Autoplete />. Does anyone have an idea?

  const [val, setVal] = useState([]);

  const valHtml = val.map((option, index) => (
    <Chip
      label={option.title}
      deleteIcon={<RemoveIcon />}
      onDelete={() => {}}
    />
  ));

  return (
    <div>
      <Autoplete
        multiple
        filterSelectedOptions
        options={top100Films}
        onChange={(e, newValue) => setVal(newValue)}
        getOptionLabel={option => option.title}
        renderTags={() => {}}
        renderInput={params => (
          <TextField
            {...params}
            variant="standard"
            placeholder="Favorites"
            margin="normal"
            fullWidth
          />
        )}
      />
      <div className="selectedTags">{valHtml}</div>
    </div>
  );
}

Complete code here

Share Improve this question asked Nov 18, 2019 at 23:46 user2683470user2683470 1891 gold badge3 silver badges15 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

You need two things:

  1. Appropriate logic in the onDelete of the Chip such as:
      onDelete={() => {
        setVal(val.filter(entry => entry !== option));
      }}
  1. Specify the value (which you are already managing in state) on the Autoplete:
      <Autoplete
        value={val}
        // ... other properties
      />

Here is a working version of your sandbox: https://codesandbox.io/s/autoplete-with-chips-85rqq

本文标签: javascriptHow to remove a selected Chip outside of Autocomplete in material UIStack Overflow