Languages
[Edit]
EN

React - Material-UI Select component with array of objects

25 points
Created by:
Root-ssh
177650

In this short article, we would like to show how to use in React project, Material-UI Select component with array of objects as options.

By default, the select component doesn't use an options array, so it is necessary to add items inside using JSX notation.

Quick solution:

// import React, { useEffect, useState } from 'react';

// import Select from '@material-ui/core/Select/Select';
// import MenuItem from '@material-ui/core/MenuItem/MenuItem';

const options = [
    {label: 'React',      value: 'react'},
    {label: 'JavaScript', value: 'js'   },
    {label: 'TypeScript', value: 'ts'   }
];

return (
    <Select name={name} value={value}>
      {options?.map(option => {
          return (
            <MenuItem key={option.value} value={option.value}>
              {option.label ?? option.value}
            </MenuItem>
          );
      })}
    </Select>
);

 

Practical example

Presented solution uses controlled component mode (value and onChange).

ControlledSelect.jsx file:

import React, { useEffect, useState } from 'react';

import Select from '@material-ui/core/Select/Select';
import MenuItem from '@material-ui/core/MenuItem/MenuItem';

export const ControlledSelect = ({ name, value, options, onFocus, onChange, onBlur }) => {
    const [localValue, setLocalValue] = useState(value ?? '');  // we want to keep value locally
    useEffect(() => setLocalValue(value ?? ''), [value]);       // we want to update local value on prop value change
    const handleFocus = () => {
        if (onFocus) {
            onFocus();
        }
    };
    const handleChange = (e) => {
        const value = e.target.value;
        setLocalValue(value);
        if (onChange) {
            onChange(value);
        }
    };
    const handleBlur = (e) => {
        if (onBlur) {
            onBlur(e.target.value);
        }
    };
    return (
        <Select
          name={name}
          value={localValue}      // we want to work in controlled mode
          onFocus={handleFocus}
          onChange={handleChange} // we want to work in controlled mode
          onBlur={handleBlur}
        >
          {options?.map(option => {
              return (
                <MenuItem key={option.value} value={option.value}>
                  {option.label ?? option.value}
                </MenuItem>
              );
          })}
        </Select>
    );
};

export default ControlledSelect;

Example usage in App.jsx file:

import React, { useEffect, useState } from 'react';

import ControlledSelect from './ControlledSelect';

export const App = () => {
    const [value, setValue] = useState('react'); // selected option
    const options = [
        {label: 'React',      value: 'react'},
        {label: 'JavaScript', value: 'js'   },
        {label: 'TypeScript', value: 'ts'   }
    ];
    const handleChange = (value) => {
        conosle.log(`value: ${value}`);
        setValue(value);
    };
    return (
        <div>
          <label>Technology:</label>
          <ControlledSelect value={value} options={options} onChange={handleChange} />
        </div>
    );
};

export default App;

 

References

  1. Material-UI Select - Official Docs 

Alternative titles

  1. React- Material-UI Select component with objects as options
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - Material-UI Select component with array of objects
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join