46

I am using Select box from material-ui

I want to show "select the value" option by default selected but after that user is not able to select this option.

<FormControl required className={classes.formControl}>
  <InputLabel htmlFor="circle">Circle</InputLabel>
    <Select
      value={circle}
      onChange={event => handleInput(event, "circle")}
      input={<Input name="circle" id="circle" />}
    >
      <MenuItem value="" disabled>
        <em>select the value</em>
      </MenuItem>

      <MenuItem value={10}>Ten</MenuItem>
      <MenuItem value={20}>Twenty</MenuItem>
      <MenuItem value={30}>Thirty</MenuItem>
    </Select>
  <FormHelperText>Some important helper text</FormHelperText>
</FormControl>

Current code on sandbox: https://codesandbox.io/s/xoylmlj1qp

I want to make like this: https://jsfiddle.net/wc1mxdto/


Update

I changed the state 20 to blank string in circle

form: {
  searchValue: "",
  circle: '',
  searchCriteria: ""
}

now expected output should be dropdown should show "please select value" but currently it showing this enter image description here

JGallardo
  • 11,074
  • 10
  • 82
  • 96
user944513
  • 12,247
  • 49
  • 168
  • 318

9 Answers9

25

You can just pass the displayEmpty into select

<Select
    id="demo-simple-select-outlined"
    displayEmpty
    value={select}
    onChange={handleChange}
>

and define the menuItem like

<MenuItem value=""><Put any default Value which you want to show></MenuItem>
David Buck
  • 3,752
  • 35
  • 31
  • 35
Alok Kumar
  • 251
  • 3
  • 4
20

You need to provide correct MenuItem value in state to be matched on render.

Here is the working codesandbox: Default Select Value Material-UI

Sakhi Mansoor
  • 7,832
  • 5
  • 22
  • 37
  • 1
    sorry it is not a correct answer . instead of `20` if I am passing `""` (blank) string it should select "please select value" as shown in fiddle https://jsfiddle.net/wc1mxdto/ – user944513 Sep 05 '18 at 10:59
  • It is already showing it as default value if you pass empty string. Please elaborate your issue – Sakhi Mansoor Sep 05 '18 at 11:02
  • please see update Question.I am updating more to clear more – user944513 Sep 05 '18 at 11:06
  • see updated code i used `shrink` property in first select box https://codesandbox.io/s/j7kwpnp593 – user944513 Sep 05 '18 at 11:07
  • not when I run application it should show please select value – user944513 Sep 05 '18 at 11:08
  • see this fiddle when I run or open this link it show's "select your option" https://jsfiddle.net/wc1mxdto/2/ but after user select options but not select this option "select your option" because that is disable – user944513 Sep 05 '18 at 11:10
  • Updated my codesandbox.You need renderValue as creating a reactElement in select other than menuItems – Sakhi Mansoor Sep 05 '18 at 11:14
  • working so this select value is "select value" ?? correct ? for UI it is correct but logically it is not correct .because if I take this is `required` it is alway true..:( – user944513 Sep 05 '18 at 11:21
  • 3
    Your example is hard to follow. Using some meaningful names instead of `` and `test` would be better. – Qwerty Apr 10 '19 at 10:25
  • 5
    Sample is broken: "_typeof is not a function" – motto Nov 24 '21 at 18:38
18

As React introduced React-Hooks, you just need to pass your default value in React.useState() as React.useState(10).


export default function CustomizedSelects() {
  const classes = useStyles();
  const [age, setAge] = React.useState(10);// <--------------(Like this).
  const handleChange = event => {
    setAge(event.target.value);
  };
  return (
    <form className={classes.root} autoComplete="off">
      <FormControl className={classes.margin}>
        <Select
          value={age}
          className={classes.inner}
          onChange={handleChange}
          input={<BootstrapInput name="currency" id="currency-customized-select" />}
        >
          <MenuItem value={10}>Ten</MenuItem>
          <MenuItem value={20}>Twenty</MenuItem>
          <MenuItem value={30}>Thirty</MenuItem>
        </Select>
      </FormControl>
    </form>
  );
}


B4BIPIN
  • 353
  • 2
  • 11
  • 1
    This does not answer the question in the title *how to set a default value*. This solution sets the value fixed. Meaning, if you don't use state, the user can't change the value. – DarkTrick Jun 28 '22 at 04:42
5

<FormControl variant="outlined" className={classes.formControl}>
  <InputLabel id="uni">UNI</InputLabel>
  <Select
    key={value}
    defaultValue={value}
    labelId="uni"
    id="uni"
    name="uni"
    onBlur={onChange}
    label="uni"
  >
    {unis.map((u, i) => (
      <MenuItem value={u.value} key={i}>
        {u.label}
      </MenuItem>
    ))}
  </Select>
</FormControl>;
  • 7
    Could you please add a description to your answer about _how_ and _why_ the code snippet you've provided solves the problem? In other words: what is the root cause of the problem here, and how does your code snippet solve that? – Micheal Hill Apr 12 '20 at 03:01
  • The first solution in line providing an answer to the question in the title *how to set a default value*. – DarkTrick Jun 28 '22 at 04:45
2

Just use the defaultValue attribute of select. You can refer to the Material UI Select API Docs to know more.

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

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

const Selector = () => {
    const [Value, setValue] = useState("1");    //    "1" is the default value in this scenario. Replace it with the default value that suits your needs.
    const handleValueChange = event => {
        setValue(event.target.value);
    }

    return(
        <FormControl>
            <InputLabel id="Input label">Select</InputLabel>
                <Select
                    labelId= "Input label"
                    id= "Select"
                    value= {Value}
                    defaultValue= {Value}
                    onChange= {handleValueChange}
                >
                    <MenuItem value="1">Item1</MenuItem>
                    <MenuItem value="2">Item2</MenuItem>
                    <MenuItem value="3">Item3</MenuItem>
                </Select>
        </FormControl>
    )
};

export default Selector;
Manil Malla
  • 293
  • 2
  • 6
2

If you take a look at the Select Api of Material UI here, you could do it easily.

  1. As explained above, you need to pass the default value in your state variable:
const [age, setAge] = React.useState(10);// <--------------(Like this).
  1. Set displayEmpty to true:

If true, a value is displayed even if no items are selected. In order to display a meaningful value, a function should be passed to the renderValue prop which returns the value to be displayed when no items are selected. You can only use it when the native prop is false (default).

<Select 
  displayEmpty
/>
leuk7
  • 119
  • 3
0

I had a similar issue. In my case, I applied a function directly to onChange so I had something like this:

export default function CustomizedSelects() {
const classes = useStyles();
const [age, setAge] = React.useState(10);

return (
  <form className={classes.root} autoComplete="off">
    <FormControl className={classes.margin}>
      <Select
        value={age}
        className={classes.inner}
        onChange={(event) => setAge(event.target.value)}
        input={<BootstrapInput name="currency" id="currency-customized-select" />}
    >
      <MenuItem value={10}>Ten</MenuItem>
      <MenuItem value={20}>Twenty</MenuItem>
      <MenuItem value={30}>Thirty</MenuItem>
    </Select>
  </FormControl>
</form>

); }

I also had a separate button to clear select value (or select the default empty value). All was working, the select value was set correctly, except the Select component did not animate to its default form - when no value is selected. I fixed the problem by moving onChange to a handleChange separate function as it is in the code example @B4BIPIN is presenting.

I am not an expert in React and still learning and this was a good lesson. I hope this helps ;-)

Strabek
  • 2,391
  • 3
  • 32
  • 39
0

Take a list of objects you want to display in the Select dropdown and initialise it using useState. Use the state now to show the value and update the state on the change of the dropdown.

const ackList = [
  {
    key: 0,
    value: "Not acknowledged",
  },
  {
    key: 1,
    value: "Acknowledged",
  },
];

function AcknowledgementList() {
//state to initialise the first from the list
  const [acknowledge, setAcknowledge] = useState(ackList[1]);

//update the state's value on change
  const handleChange2 = (event) => {
    setAcknowledge(ackList[event.target.value]);
  };
  return (
            <TextField
              select
              fullWidth
              value={acknowledge.key} 
              onChange={handleChange2}
              variant="outlined"
            >
              {ackList.map((ack) => (
                <MenuItem key={ack.key} value={ack.key}>
                  {ack.value}
                </MenuItem>
              ))}
            </TextField>

    );

}
Bikash
  • 1
  • 1
  • 1
    While this code may solve the problem, [including an explanation](https://meta.stackexchange.com/q/114762) really helps to improve the quality of your answer. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, as this reduces the readability of both the code and the explanations. – padaleiana Aug 18 '21 at 14:40
0

The problem here is all to do with some pretty poor coding on the part of the MUI folks, where on several components, they have magic strings and really are doing silly things.

Let's take a look at the state here:

const [age, setAge] = React.useState('3');

You can see that we are having to specify the VALUE as a string. Indeed the data type that the Select control takes is a string | undefined. So the fact we are having to use a number value as a string is the source of confusion.

So how does that work?

It is all to do with the MenuItem component. Let's take a look:

<MenuItem value={1}>First Choice</MenuItem>
<MenuItem value={2}>Second Choice</MenuItem>
<MenuItem value={3}>Third Choice</MenuItem>

You can see that we are indeed having to specify the VALUE of the MenuItem as a number.

So in this case, specifying '3' as the State value, as a string, will select the Third Choice on load.

You can set the VALUE in the Select control as the state value.

Don't forget, when handling the onChange event, that you will need to convert the event.target.value to string.