How to make mui autocomplete with chips in react js?
January 11, 2023Hi Friends 👋,
Welcome To aGuideHub!
To make mui autocomplete with chips in React js, you can use <Chip variant="outlined" label={option} {...getTagProps({ index })} />
in autocomplete render tags attribute. It will make mui autocomplete with chips.
Today, I am going to show you, how to make mui autocomplete with chips in react js.
Installation
Install the following packages to use make mui autocomplete with chips in react js.
npm
npm install @mui/material @emotion/react @emotion/styled
yarn
yarn add @mui/material @emotion/react @emotion/styled
MUI material make mui autocomplete with chips example.
The below code is an example of a Material UI autocomplete chips.
You have to import @mui material
autocomplete and use <Chip variant="outlined" label={option} {...getTagProps({ index })} />
in autocomplete render tags attribute. It will made mui autocomplete with chips.
App.js
import * as React from 'react';
import Chip from '@mui/material/Chip';
import Autocomplete from '@mui/material/Autocomplete';
import TextField from '@mui/material/TextField';
import Stack from '@mui/material/Stack';
export default function Tags() {
return (
<Stack spacing={3} sx={{ width: 500 }}>
<Autocomplete
multiple
id="tags-filled"
options={top100Films.map((option) => option.title)}
defaultValue={[top100Films[13].title]}
freeSolo
renderTags={(value, getTagProps) =>
value.map((option, index) => (
<Chip variant="outlined" label={option} {...getTagProps({ index })} />
))
}
renderInput={(params) => (
<TextField
{...params}
variant="filled"
label="freeSolo"
placeholder="Favorites"
/>
)}
/>
</Stack>
);
}
// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films = [
{ title: 'The Shawshank Redemption', year: 1994 },
{ title: 'The Godfather', year: 1972 },
{ title: 'The Godfather: Part II', year: 1974 },
{ title: 'The Dark Knight', year: 2008 },
{ title: '12 Angry Men', year: 1957 },
{ title: "Schindler's List", year: 1993 },
{ title: 'Pulp Fiction', year: 1994 },
{
title: 'The Lord of the Rings: The Return of the King',
year: 2003,
},
{ title: 'The Good, the Bad and the Ugly', year: 1966 },
{ title: 'Fight Club', year: 1999 },
{
title: 'The Lord of the Rings: The Fellowship of the Ring',
year: 2001,
},
{
title: 'Star Wars: Episode V - The Empire Strikes Back',
year: 1980,
},
{ title: 'Forrest Gump', year: 1994 },
{ title: 'Inception', year: 2010 },
{
title: 'The Lord of the Rings: The Two Towers',
year: 2002,
},
{ title: 'Monty Python and the Holy Grail', year: 1975 },
];
In the above code example, I have used the @mui/material
component and make mui autocomplete with chips in react js.
Check the output of the above code example.
All the best 👍