javascriptreactjsmaterial-ui

How to show custom value in TextField type of select?


Here is my component. So when I select e.g. "Option 1" in dropdown I want to show in TextField this selected item like e.g. "Option 1 selected". Please advise

import React from 'react';
import { TextField, MenuItem } from '@mui/material';

const MyComponent = () => {
  const [selectedOption, setSelectedOption] = React.useState('');

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

  return (
    <TextField id="select-option" select label="Select an option" value={selectedOption} onChange={handleChange}>
      <MenuItem value="option1">Option 1</MenuItem>
      <MenuItem value="option2">Option 2</MenuItem>
      <MenuItem value="option3">Option 3</MenuItem>
    </TextField>
  );
};

export default MyComponent;

Solution

  • You can achieve this using the slotProps.select.renderValue prop. You could try something like this:

    import React from 'react';
    import { TextField, MenuItem } from '@mui/material';
    
    const MyComponent = () => {
      const [selectedOption, setSelectedOption] = React.useState('');
    
      const options = [
        { id: 'option1', name: 'Option 1' },
        { id: 'option2', name: 'Option 2' },
        { id: 'option3', name: 'Option 3' },
      ];
    
      return (
        <TextField
          select
          fullWidth
          label="Select an option"
          value={selectedOption}
          onChange={(e) => setSelectedOption(e.target.value)}
          slotProps={{
            select: {
              renderValue: (selected) => {
                const selectedItem = options.find(opt => opt.id === selected);
                return selectedItem ? `${selectedItem.name} selected` : '';
              }
            }
          }}
        >
          {options.map((option) => (
            <MenuItem key={option.id} value={option.id}>
              {option.name}
            </MenuItem>
          ))}
        </TextField>
      );
    };
    

    When you use the select prop on TextField, it renders a Select element and passes the Input as its input component. Through slotProps.select, you can access the full Select API, including the renderValue prop used here. Alternatively, you could use the Select component directly.