Search code examples
javascriptreactjsselectecmascript-6html-select

How to make a default selected select react attribue a string?


I'm trying to make a default selected select react attribue a string. Is it possible with react?

https://codesandbox.io/s/test-login-page-tasks-forked-vkxnxg?file=/src/components/NewTask.js

//react child component

const Component = () => {
  return (
<select value={"select an option"}>        /// place a string here
  <option>
    Option 1
  </option>
  <option >
    Option 2
  </option>
</select>
}


Solution

  • Based on the sandbox shared, you can have a disabled option with some value and then set the defaultValue of select the same value

            <select onChange={(e) => setAuthor(e.target.value)} defaultValue="select an option" >
              <option value="select an option" disabled>
                Select author
              </option>
              {authors.map((author) => (
                <option key={author.author_name} value={author.author_name}>
                  {author.author_name}
                </option>
              ))}
            </select>