Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving the chips/tags outside Autocomplete box in MUI

I am using the MUI Autocomplete component and am trying to figure out if it is possible to move the chips/tags outside of the input box. Is this even possible? I would prefer if the chips were listed just underneath the box instead. This way the text box can be used solely for the user input and not both displaying the chips/tags & user input.

I have tried to play with one of the basic demo's but didn't have any luck. I cleared it back to the default state in case there are some users here that have experience with this. A starting point for an example can be the following sandbox

https://codesandbox.io/s/material-demo-forked-7vroo?file=/demo.js

like image 782
Fivestar Avatar asked Mar 31 '21 03:03

Fivestar


1 Answers

You can do that by disabling tag rendering inside Autocomplete and add your own Chip list below the Autocomplete.

const [value, setValue] = useState([]);
const onDelete = (title) => () => {
  setValue((value) => value.filter((v) => v.title !== title));
};

return (
  <Box sx={{ width: 500 }}>
    <Autocomplete
      multiple
      options={top100Films}
      defaultValue={[top100Films[13]]}
      getOptionLabel={(option) => option.title}
      value={value}
      onChange={(e, newValue) => setValue(newValue)}
      renderTags={() => null}
      renderInput={(params) => (
        <TextField {...params} variant="outlined" placeholder="Favorites" />
      )}
    />
    <Box
      mt={3}
      sx={{
        '& > :not(:last-child)': { marginRight: 1 },
        '& > *': { marginBottom: 1 },
      }}
    >
      {value.map((v) => (
        <Chip key={v.title} label={v.title} onDelete={onDelete(v.title)} />
      ))}
    </Box>
  </Box>
);
const top100Films = [
  { title: "The Shawshank Redemption", year: 1994 },
  { title: "The Godfather", year: 1972 },
]

Live Demo

V5

Edit 66881433/moving-the-chips-tags-out-of-the-autocomplete-box-in-material-ui (forked)

V4

Edit 66881433/moving-the-chips-tags-out-of-the-autocomplete-box-in-material-ui

like image 67
NearHuscarl Avatar answered Nov 15 '22 03:11

NearHuscarl