React 18 Material UI Select Dropdown Component Example Tutorial

Last Updated on by in React JS

A select component is a widely used UI component for accumulating user-provided information from a given list of options.

If you want to create a select box quickly, then we have a powerful solution for you.

In this tutorial, we will learn how to create a select component in React function component using React Material UI package.

Throughout this React Select dropdown example, we will show you how to build a basic select dropdown and how to create a native select component in React.

Furthermore, you will also discover how to customize the select component in React application.

MUI offers a simple, subtle, customizable, and accessible library of React components.

It is easy to install, and yes, it easily aligns with your design system.

How to Create Select Dropdown in React JS using React Material UI

  • Step 1: Create New Project
  • Step 2: Install React Material UI Package
  • Step 3: Make Function Component
  • Step 4: Build Select Dropdown Component
  • Step 5: Create Multiple Select Dropdown
  • Step 6: Auto Width Select Dropdown
  • Step 7: Build Native Select Component
  • Step 9: Update App JS Component
  • Step 10: Run App on Browser

Create New Project

We are now going to take the first step by installing a new React app. You can directly jump on to the subsequent step if you have already created the app.

npx create-react-app react-blog-app

Install React Material UI Package

In the given code snippet, you will find the specific commands. These commands will allow you to install React MUI and its core dependencies.

npm i @mui/material @emotion/react @emotion/styled --legacy-peer-deps
npm install @fontsource/roboto --legacy-peer-deps

Furthermore, we will register the font family by importing in the App.css file.

@import url("https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap");
@import "@fontsource/roboto/300.css";
@import "@fontsource/roboto/400.css";
@import "@fontsource/roboto/500.css";
@import "@fontsource/roboto/700.css";

Make Function Component

After the app is generated and fonts are registered, we will make the function component.

Hence, make the components/ folder, then create the UserForm.js file.

import React from 'react'

function UserForm() {
  return (
    <div>UserForm</div>
  )
}

export default UserForm

Build Select Dropdown Component

We will show you how to implement a basic select box in React.

We will create a simple age select dropdown component, make sure to import Box, InputLabel, MenuItem, FormControl and Select modules from their packages.

Add code into the components/UserForm.js file.

import * as React from "react";
import Box from "@mui/material/Box";
import InputLabel from "@mui/material/InputLabel";
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import Select from "@mui/material/Select";

export default function UserForm() {
  const [age, setAge] = React.useState("");

  const handleChange = (e) => {
    setAge(e.target.value);
  };

  return (
    <Box sx={{ minWidth: 120 }}>
      <FormControl fullWidth>
        <InputLabel id="demo-simple-select-label">Choose age</InputLabel>
        <Select
          labelId="demo-simple-select-label"
          id="demo-simple-select"
          value={age}
          label="Age"
          onChange={handleChange}
        >
          <MenuItem value={10}>Ten</MenuItem>
          <MenuItem value={20}>Twenty</MenuItem>
          <MenuItem value={30}>Thirty</MenuItem>
        </Select>
      </FormControl>
    </Box>
  );
}

Create Multiple Select Dropdown

React MUI offers a powerful way to use the Select component; It allows you to handle multiple selections at a single go.

The following code snippet enables multiple props.

Same as the single selection, we can grab the new value by accessing the event.target.value aligining the onChange event handler.

import * as React from "react";
import { useTheme } from "@mui/material/styles";
import OutlinedInput from "@mui/material/OutlinedInput";
import InputLabel from "@mui/material/InputLabel";
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import Select from "@mui/material/Select";

const ITEM_HEIGHT = 48;
const ITEM_PADDING_TOP = 8;
const MenuProps = {
  PaperProps: {
    style: {
      maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
      width: 250,
    },
  },
};

const names = [
  "Oliver Hansen",
  "Van Henry",
  "April Tucker",
  "Ralph Hubbard",
  "Omar Alexander",
  "Carlos Abbott",
  "Miriam Wagner",
  "Bradley Wilkerson",
  "Virginia Andrews",
  "Kelly Snyder",
];

function getStyles(name, personName, theme) {
  return {
    fontWeight:
      personName.indexOf(name) === -1
        ? theme.typography.fontWeightRegular
        : theme.typography.fontWeightMedium,
  };
}

export default function UserForm() {
  const theme = useTheme();
  const [personName, setPersonName] = React.useState([]);

  const handleChange = (event) => {
    const {
      target: { value },
    } = event;
    setPersonName(
      // On autofill we get a stringified value.
      typeof value === "string" ? value.split(",") : value
    );
  };

  return (
    <div>
      <FormControl sx={{ m: 1, width: 300 }}>
        <InputLabel id="demo-multiple-name-label">Name</InputLabel>
        <Select
          labelId="demo-multiple-name-label"
          id="demo-multiple-name"
          multiple
          value={personName}
          onChange={handleChange}
          input={<OutlinedInput label="Name" />}
          MenuProps={MenuProps}
        >
          {names.map((name) => (
            <MenuItem
              key={name}
              value={name}
              style={getStyles(name, personName, theme)}
            >
              {name}
            </MenuItem>
          ))}
        </Select>
      </FormControl>
    </div>
  );
}

Auto Width Select Dropdown

We can change the width of the select box; instead of a fixed width we can set the auto width to the select component.

import * as React from "react";
import InputLabel from "@mui/material/InputLabel";
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import Select from "@mui/material/Select";

export default function UserForm() {
  const [age, setAge] = React.useState("");

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

  return (
    <div>
      <FormControl sx={{ m: 1, minWidth: 80 }}>
        <InputLabel id="demo-simple-select-autowidth-label">Age</InputLabel>
        <Select
          labelId="demo-simple-select-autowidth-label"
          id="demo-simple-select-autowidth"
          value={age}
          onChange={handleChange}
          autoWidth
          label="Age"
        >
          <MenuItem value="">
            <em>None</em>
          </MenuItem>
          <MenuItem value={10}>Twenty</MenuItem>
          <MenuItem value={21}>Twenty one</MenuItem>
          <MenuItem value={22}>Twenty one and a half</MenuItem>
        </Select>
      </FormControl>
    </div>
  );
}

Build Native Select Component

In modern days we are not only concerned with the desktop view.

We need to create UI components which equally support mobile view; therefore, we are creating native select in React to enrich the user-experience.

import * as React from 'react';
import Box from '@mui/material/Box';
import InputLabel from '@mui/material/InputLabel';
import FormControl from '@mui/material/FormControl';
import NativeSelect from '@mui/material/NativeSelect';

export default function UserForm() {
  return (
    <Box sx={{ minWidth: 120 }}>
      <FormControl fullWidth>
        <InputLabel variant="standard" htmlFor="uncontrolled-native">
          Age
        </InputLabel>
        <NativeSelect
          defaultValue={30}
          inputProps={{
            name: 'age',
            id: 'uncontrolled-native',
          }}
        >
          <option value={10}>Ten</option>
          <option value={20}>Twenty</option>
          <option value={30}>Thirty</option>
        </NativeSelect>
      </FormControl>
    </Box>
  );
}

Update App JS Component

Now, the further task is to inject the UserForm component into the global App.js file.

This process will register the component and run the feature in the application.

import React from "react";
import UserForm from "./components/UserForm";

function App() {
  return (
    <div>
      <h2>React Material UI Select Dropdown Example</h2>
      <UserForm />
    </div>
  );
}

export default App;

Run App on Browser

Now that you have the utter idea of how to integrate React Select UI component in React environment.

Let’s see how it works on the browser.

npm start

Start the app using the given url only if you create the feature locally.

http://localhost:3000

React Material UI Select Dropdown Component Example Tutorial

Conclusion

In this guide, we learned how to implement a select dropdown in React JS app using React Material UI.

Furthermore, we also discovered how to customize the select component using the React MUI custom properties.

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.