react mui 5 search bar example

React MUI 5 Search Bar Example

November 25, 2023 By Aaronn

In this tutorial, we will how to create search bar in react with material ui (mui 5). We will see search bar with hook, search bar with search icon, example with react material UI 5.

Install & Setup Vite + React + Typescript + MUI 5


React Material UI 5 Search Bar Example

1.react mui 5 simple search bar.

import { Container, TextField } from "@mui/material";

export default function SearchBar() {
  return (
    <>
      <Container maxWidth="md" sx={{ mt: 20 }}>
        <TextField  type="search" id="search" label="Search" sx={{ width: 600 }} />
      </Container>
    </>
  );
}
react mui 5 search bar

react mui 5 search bar

2.react mui 5 standard search bar.

import { Container, TextField } from "@mui/material";

export default function SearchBar() {
  return (
    <>
      <Container maxWidth="md" sx={{ mt: 20 }}>
        <TextField
          id="standard-search"
          label="Search field"
          type="search"
          variant="standard"
          sx={{ width: 400 }}
        />
      </Container>
    </>
  );
}
mui 5 standard search bar

mui 5 standard search bar

3.react mui 5 search bar onchange value with useState hooks.

import { TextField } from '@mui/material';
import { useState } from 'react';

export default function SearchBar() {
  const [searchTerm, setSearchTerm] = useState('');

  const handleChange = (event) => {
    setSearchTerm(event.target.value);
  };

  return (
    <TextField
      id="search"
      type="search"
      label="Search"
      value={searchTerm}
      onChange={handleChange}
      sx={{ width: 600 }}
    />
  );
}


4. react mui 5 search bar with icons. Before using icons in search you need to install @mui/icons-material.

Install the package in your project directory with:

# with npm
npm install @mui/icons-material

# with yarn
yarn add @mui/icons-material

react mui 5 search bar with search icon.

import { Container, InputAdornment, TextField } from "@mui/material";
import { useState } from "react";
import SearchIcon from "@mui/icons-material/Search";

export default function SearchBar() {
  const [searchTerm, setSearchTerm] = useState("");

  const handleChange = (event) => {
    setSearchTerm(event.target.value);
  };

  return (
    <Container maxWidth="md" sx={{ mt: 20 }}>
      <TextField
        id="search"
        type="search"
        label="Search"
        value={searchTerm}
        onChange={handleChange}
        sx={{ width: 600 }}
        InputProps={{
          endAdornment: (
            <InputAdornment position="end">
              <SearchIcon />
            </InputAdornment>
          ),
        }}
      />
    </Container>
  );
}
react mui 5 search bar with search icon

react mui 5 search bar with search icon

5. Create a search bar with icon using React MUI 5 and TypeScript.

import React, { useState } from 'react';
import { InputBase, Paper, IconButton } from '@mui/material';
import SearchIcon from '@mui/icons-material/Search';

const SearchBar: React.FC = () => {
  const [searchTerm, setSearchTerm] = useState<string>('');

  const handleSearch = (event: React.FormEvent) => {
    event.preventDefault();
    // Handle the search logic here
    console.log(searchTerm);
  };

  return (
    <Paper
      component="form"
      onSubmit={handleSearch}
      sx={{ p: '2px 4px', display: 'flex', alignItems: 'center', width: 400 }}
    >
      <InputBase
        sx={{ ml: 1, flex: 1 }}
        placeholder="Search..."
        inputProps={{ 'aria-label': 'search google maps' }}
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
      />
      <IconButton type="submit" sx={{ p: '10px' }} aria-label="search">
        <SearchIcon />
      </IconButton>
    </Paper>
  );
};

export default SearchBar;


6. Build a search bar in React MUI 5 with TypeScript, utilizing the JSONPlaceholder fake API.

import React, { useState, useEffect } from 'react';
import { InputBase, Paper, IconButton, List, ListItem } from '@mui/material';
import SearchIcon from '@mui/icons-material/Search';

interface User {
  id: number;
  name: string;
}

const App: React.FC = () => {
  const [searchTerm, setSearchTerm] = useState<string>('');
  const [users, setUsers] = useState<User[]>([]);
  const [filteredUsers, setFilteredUsers] = useState<User[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(false);

  useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);
      try {
        const response = await fetch('https://jsonplaceholder.typicode.com/users');
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        const data: User[] = await response.json();
        setUsers(data);
      } catch (error) {
        console.error('Error fetching data:', error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchData();
  }, []);

  const handleSearch = (event: React.ChangeEvent<HTMLInputElement>) => {
    const value = event.target.value;
    setSearchTerm(value);

    const filtered = users.filter(user =>
      user.name.toLowerCase().includes(value.toLowerCase())
    );
    setFilteredUsers(filtered);
  };

  return (
    <div>
      <Paper
        component="form"
        sx={{ p: '2px 4px', display: 'flex', alignItems: 'center', width: 400 }}
      >
        <InputBase
          sx={{ ml: 1, flex: 1 }}
          placeholder="Search users..."
          inputProps={{ 'aria-label': 'search users' }}
          value={searchTerm}
          onChange={handleSearch}
        />
        <IconButton sx={{ p: '10px' }} aria-label="search">
          <SearchIcon />
        </IconButton>
      </Paper>
      {isLoading ? (
        <div>Loading...</div>
      ) : (
        <List>
          {filteredUsers.map((user) => (
            <ListItem key={user.id}>{user.name}</ListItem>
          ))}
        </List>
      )}
    </div>
  );
};

export default App;
react mui 5 search bar with fake api

react mui 5 search bar with fake api


Related Posts

create a chat ui in react with mui 5

create a blog section in react mui 5

create a footer in react mui 5

create a responsive navbar in react with mui 5

react mui 5 slider example

react mui 5 sidebar example

react mui 5 404 page example

react mui 5 login page example

react mui 5 image list example

react mui 5 registration form example

react mui 5 contact us page example

react mui 5 loading skeleton example

react mui 5 gradient button example

react mui 5 social media icons example

react mui 5 snackbar toast notification example

how to use autocomplete react mui 5

dynamically multiple input fields in react mui 5

how to use dropdown menu in react mui 5

how to use background image in react mui 5

how to use pricing table in react mui 5

how to use dark mode in react mui 5

how to use file upload in react mui 5

how to use sticky navbar in react mui 5

how to use box shadow in react mui 5

how to use multi step form in react mui 5

how to use loading button in react mui 5