Search code examples
reactjsformsselectdefault-value

How to use defaultValue in the select tag in a functional component?


I have a functional component that contains a select tag with a few options.
I want to set cars as the default value.
Initially, I simply added selected in the car's option but react gave me a warning saying I should be using defaultValue in the select tag instead. I was wondering how I can do that?

Thanks in advance.

function ChooseOptions(props) {
  return (
    <div>
      <h2>Choose Options</h2>
      <label>
        New Only <input type="checkbox" />
      </label>

      <label
        htmlFor="selectType"
        style={{ display: "block" }}
        defaultValue="Cars"
      >
        Select Type
        <select id="selectType">
          <option value="all">All</option>
          <option value="cars">Cars</option>
          <option value="trucks">Trucks</option>
          <option value="convertibles">Convertibles</option>
        </select>
      </label>
    </div>
  );
}

Solution

  • Try this.

    You will get the change value in 'onChange' props,

    You can set value by passing 'value' props

      <select id="selectType" defaultValue="cars">
                <option value="all">All</option>
                <option value="cars">Cars</option>
                <option value="trucks">Trucks</option>
                <option value="convertibles">Convertibles</option>
            </select>