Languages
[Edit]
EN

React - Material-UI Select component with array of objects

7 points
Created by:
Root-ssh
94100

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. Presented solution uses controlled component mode (value and onChange).

Quick solution as 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((item) => {
        return (
          <MenuItem key={item.value} value={item.value}>
            {item.label ?? item.value}
          </MenuItem>
        );
      })}
    </Select>
  );
};

export default ControlledSelect;

Example usage as 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 

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