0

I have <InputLabel> and Select and MenuItem components used in the code as follows:

<div className="form-field full-width-field ">
                   
                    <InputLabel>Q3.Is this the correct data?</InputLabel>
                        <Select
                        labelId="demo-simple-select-label"
                        id="demo-simple-select"
                        value={''}
                       onChange={handleChange}
                        >
                        <MenuItem value={'Y'}>Yes</MenuItem>
                        <MenuItem value={'N'}>No</MenuItem>
                        
                        </Select>
                    </div>

So, when I use value = {''} as shown above in the Select, I don't see any error in the code. However, when a user selects Yes or No, nothing is displayed on the screen, as shown below:

enter image description here

However, when I comment out the value = {''} part and use it like this:

                     <Select
                        labelId="demo-simple-select-label"
                        id="demo-simple-select"
                        //value={''}
                       onChange={handleChange}
                        >

It displays the user selection Yes or No on the screen but I keep getting following warning in the console i nred color:

Warning: A component is changing an uncontrolled input of type undefined to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.

How can I fix both the issues?

Tan
  • 1,433
  • 5
  • 27
  • 47
  • Use `defaultValue` attribute instead of `value` attribute. Read more here - https://reactjs.org/docs/uncontrolled-components.html – Srishti Gupta May 15 '21 at 01:49

1 Answers1

0

Make your component controlled.

const [answer, setAnswer] = useState('');

function handleChange(event) {
    setAnswer(event.target.value);
}

<div className="form-field full-width-field ">
    <InputLabel>Q3.Is this the correct data?</InputLabel>
    <Select labelId="demo-simple-select-label"
            id="demo-simple-select"
            value={answer}
            onChange={handleChange}>
        <MenuItem value={'Y'}>Yes</MenuItem>
        <MenuItem value={'N'}>No</MenuItem>                        
    </Select>
</div>
Ken Bekov
  • 13,696
  • 3
  • 36
  • 44
  • Thank you. I will try this. Quick question - I have couple of more dropdown similar to what I showed in my post. Would you recommend me to define two more `userState('')` for other two dropdowns as well? For example - `const [answer1, setAnswer1] = useState('');` & `const [answer2, setAnswer2] = useState('');` ? – Tan May 16 '21 at 02:36
  • @Tan yes if you have a kind of form I would recommend to define state for every field. This is a way haw controlled inputs work in React – Ken Bekov May 16 '21 at 06:08