0
<select value={author} onChange={({ target }) => setAuthor(target.value)} >
          {authors.map(author => 
            <option key={author.name} value={author.name}>
              {author.name}
            </option>)}
        </select>

This is in React/NodeJS. Everything works as expected, and the first option/author.name is displayed by default. However, it is not being set as the default value for the React state, and clicking on the dropdown and then selecting it does not change this. If another option is selected and then you select the first option, it works as expected.

studstill
  • 65
  • 1
  • 10
  • 1
    https://stackoverflow.com/a/44787318/4546364 –  Oct 22 '21 at 20:12
  • Probably the value that you set in the select does not equal any of the options. I noticed that the options have the author names as the values, but you have actually used a whole author object as the value of the select element. Is the author expression that you pass as the select value a string representing a name ? Is there an option having the same value as that name ? – Enrico Massone Oct 22 '21 at 20:16
  • 1
    Try to console.log the value of the author expression and the values of each option in your render method. The first time render is executed, I expect the value of the author expression not to equal any of the option values. That's why the select element doesn't have the initial value you would expect and the very first options is selected. – Enrico Massone Oct 22 '21 at 20:22

1 Answers1

1

You need to set the state (author in this case) for the first time manually, because the onChange event only fires when you change the selected option, so it does not set the state when it loads. you have two option:

  1. If authors known before hand you can use this:

const [author,setAuthor] = useState(authors[0].name)

  1. If you load authors asynchronously you can wait for them to load and then set the author using useEffect:
useEffect(()=>{
if(authors && authors.length>0){
setAuthor(authors[0].name);
},[authors])
Ako
  • 1,424
  • 12
  • 18