Pranav
Pranav

Reputation: 1646

How to set default value in drop down list in Material UI?

I'am creating drop down list for countries and its relevant country code. I want to set default value as '+xx' which is for particular country, but, its displayed as country as well as its respective code. How to hide country name, but, display only in drop down, i.e, country name as well as code.

Following is the code for reference

const countries = [
  {
    value: "US",
    label: "+1"
  },
  {
    value: "UK",
    label: "+44"
  },
  {
    value: "SA",
    label: "+27"
  },
  {
    value: "IND",
    label: "+91"
  }
];


  const [countryCode, setCountryCode] = React.useState("+91");

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

return (
<TextField
          id="standard-select-currency"
          select
          label="Select"
          value={countryCode}
          onChange={handleChange}
          helperText="Please select your Country"
        >
          {countries.map((option) => (
            <MenuItem key={option.value} value={option.label}>
              <p>{option.label}</p>
              <p>{option.value}</p>
            </MenuItem>
          ))}
        </TextField>
)


enter image description here

As you can see above in the image Country name is also seen which I want to hide. So, what is the best solution?

Below is the codesandbox link: https://codesandbox.io/s/material-demo-forked-kgkcd

Upvotes: 2

Views: 8788

Answers (1)

Arun Kumar Mohan
Arun Kumar Mohan

Reputation: 11905

You can use the Select component's renderValue prop to customize the displayed value. You can pass the select props to the TextField component through the SelectProps prop.

<TextField
  select
  label="Country Code"
  value={countryCode}
  onChange={handleChange}
  SelectProps={{
    renderValue: (value) => value,
  }}
>
  ...
</TextField>

Edit on CodeSandbox

Upvotes: 1

Related Questions