How to Create a React Search Bar using MUI? [with ready-made GitHub Repo]
Create a react autosuggest search bar using MUI with just 6 simple steps.
If you are just starting out with React, creating a react search bar with suggestions may initially seem difficult to build.
Fortunately, multiple React libraries are available to help you quickly build a react search bar.
In this post, I’ll help you create a fully functional search bar with suggestions in react.
Prerequisites
However, to follow this tutorial, you need to have the following:
- Node, npm, and create-react-app installed on your computer
- Basic knowledge of javascript and React js
Step By Step Guide to Creating a React Search Bar using MUI
Step 1: Create a new React App
Create a new folder in VS-code, and in the terminal, paste the following code to create a fresh new react app.
npx create-react-app react-search-bar
Go to the created new app, and remove all the unnecessary files. After that, you’re ready to build the search bar.
Step 2: Install Material UI and Axios
Before start working, you need to install two main libraries.
Run the following code in the root folder of your app and wait for it to install.
npm i axios @mui/material @emotion/react @emotion/styled
Step 3: Create the Search Bar
In the App.js
, import Typography, Box, TextField, and Autocomplete
from Material UI, and create the search bar component.
Material UI has one in-built Autocomplete component we can use as it is. Below is the exact code for the react search bar component:
import { useState, useEffect } from 'react';
import './App.css';
import { Typography, Box, TextField, Autocomplete } from '@mui/material'
import FilterPrducts from './filterProducts';
import { fetchdata } from './fetchdata';
function App() {
return (
<Box className="App"
sx={{
width: 400,
height: 660,
margin: '100px auto',
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-evenly'
}}>
<Typography variant='h4' component={'h1'}>React Search Bar</Typography>
<Autocomplete
disablePortal
id="combo-box-demo"
renderInput={(params) => <TextField {...params}
label="Search title"
sx={{
width: 350,
margin: '10px auto',
}} />}
/>
</Box>
);
}
export default App;
You may notice that we are importing fetchdata
, and FilterProducts
in the App.js
.
These are for getting dummy data and creating the logic behind the search, respectively.
Let’s see how it’s done step-by-step.
Step 4: Getting the Dummy Product Data
Create a new file in your src folder called fetchdata.jsx
.
This file will fetch dummy product data using dummyJSON API.
Here’s the code for you:
import React from "react";
import axios from 'axios'
export const fetchdata = async ()=>{
try{
const response = await axios.get('https://dummyjson.com/products')
return response.data.products
}
catch (error) {
console.log(error);
}
}
- To use the product data in your app, import
fetchdata
intoApp.js
. - With useEffect, and useState to set the data into a list constant.
- We’ll also pass down the list to the
FilterPorducts
component as props.
const [list, setList] = useState([]);
useEffect(() => {
fetchdata()
.then(res => setList(res))
}, [])
Step 5: Getting User Input
- In the
Autocomplete
search bar, we need to store the input in a constant. - We can do that easily with onSelect event handler on the text field, where the state changes every time when the user selects anything.
- We’ll also pass down the input to the
FilterProducts
component as props.
The final App.js
should look like the following:
import { useState, useEffect } from 'react';
import './App.css';
import { Typography, Box, TextField, Autocomplete } from '@mui/material'
import FilterPrducts from './filterProducts';
import { fetchdata } from './fetchdata';
function App() {
const [input, setInput] = useState('')
const [list, setList] = useState([]);
const handleInput = (e) => {
console.log(e.target.value)
setInput(e.target.value.toLowerCase())
}
useEffect(() => {
fetchdata()
.then(res => setList(res))
}, [])
return (
<Box className="App"
sx={{
width: 400,
height: 660,
margin: '100px auto',
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-evenly'
}}>
<Typography variant='h4' component={'h1'}>React Search Bar</Typography>
<Autocomplete
disablePortal
id="combo-box-demo"
options={list.map(item => item.title)}
renderInput={(params) => <TextField {...params}
label="Search title"
onSelect={handleInput}
sx={{
width: 350,
margin: '10px auto',
}} />}
/>
<FilterPrducts searchstring={input} list={list} />
</Box>
);
}
export default App;
Step 6: Filtering Through Search Result
- Create a new react component `filterProducts.jsx.
- Create a new array,
filteredList
- Using the array filter function filter the dummy data based on input.
- The search input and dummydata can be accessed by props.
- The final
filterProducts.jsx
should look like the following:
import React, { useEffect, useState } from 'react'
import { Stack } from '@mui/system';
import { Paper, Box, Typography } from '@mui/material';
export default function FilterPrducts({searchstring, list}) {
const filteredList = list.filter((element) => {
if (searchstring === '') {
return element;
}
else {
return element.title.toLowerCase().includes(searchstring)
}
})
return (
<Box>
<Stack spacing={2}
sx={{
overflow: 'auto',
maxHeight: 500,
}}
>
{filteredList.map((item) => (
<Paper key={item.id}
sx={{
textAlign:'left'
}} >
<Typography><strong>Title:</strong> {item.title}</Typography>
<Typography><strong>Desc:</strong> {item.description}</Typography>
<Typography><strong>Price:</strong> {item.price}</Typography>
<Typography><strong>Rating:</strong> {item.rating}</Typography>
<Typography><strong>Brand:</strong> {item.brand}</Typography>
</Paper>
))}
</Stack>
</Box>
)
}
Final Result
Once you are done with the entire code, the final result will look like this:
That’s it for today.
You can find the GitHub Repo here.
If you need further help, you can connect with me on LinkedIn and Twitter
Go to my Portfolio
Read my other blogs: