How to make mui list with search in react js?
February 26, 2024Hi Friends 👋,
Welcome To aGuideHub!
To make mui list with search in react js, you can create listItems.filter((item) => item.toLowerCase().includes(searchTerm.toLowerCase()));
. It will make mui list with search in React JS.
Today, I am going to show you, How to make mui list with search in react js
Installation
Install the following packages mui list in react js.
npm
npm install @mui/material @emotion/react @emotion/styled
yarn
yarn add @mui/material @emotion/react @emotion/styled
Table of contents
- Install MUI and create a new React app.
- Import Material-UI list.
- Use the list Component.
Step 1: Install MUI and create a new React app.
First you have to install the React project. You should use create-react-app
command to create a new React project.
npx create-react-app my-app
cd my-app
npm start
Step 2: Import Material-UI list.
After installing MUI
, you have to import your React component. To do this, add the following line to the top of your component file.
import React, { useState } from 'react';
import { List, ListItem, TextField } from '@mui/material';
Step 3: Use the list Component.
Lists are a continuous group of text or images. They are composed of items containing primary and supplemental actions, which are represented by icons and text.
<TextField
label="Search"
variant="outlined"
value={searchTerm}
onChange={handleSearchChange}
style={{ marginBottom: '1rem' }}
/>
<List>
{filteredListItems.map((item, index) => (
<ListItem key={index}>{item}</ListItem>
))}
</List>
MUI material make mui list with search example.
The below code is an example, you need to import list
Component. Then, you can create listItems.filter((item) => item.toLowerCase().includes(searchTerm.toLowerCase()) );
. Then it will make mui list with search in react js.
App.js
import React, { useState } from 'react';
import { List, ListItem, TextField } from '@mui/material';
function ListWithSearch() {
const [searchTerm, setSearchTerm] = useState('');
const [listItems, setListItems] = useState([
'Apple',
'Banana',
'Orange',
'Pineapple',
'Grapes',
]);
const handleSearchChange = (event) => {
setSearchTerm(event.target.value);
};
const filteredListItems = listItems.filter((item) =>
item.toLowerCase().includes(searchTerm.toLowerCase())
);
return (
<div>
<TextField
label="Search"
variant="outlined"
value={searchTerm}
onChange={handleSearchChange}
style={{ marginBottom: '1rem' }}
/>
<List>
{filteredListItems.map((item, index) => (
<ListItem key={index}>{item}</ListItem>
))}
</List>
</div>
);
}
export default ListWithSearch;
In the above code example, I have used the @mui/material
component and made mui list with search in react js.
All the best 👍