user16463210
user16463210

Reputation:

React Select Option value when no change

How to get the select value if there is no change?

<select onChange={handleChange}>
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="C">C</option>
    <option value="D">D</option>
</select>

Scenario:-

If the user selects B I want to send that value to handleChange function.

If the user does not select an option then I want A to be sent to handleChange function.

How to achieve this in react?

Upvotes: 1

Views: 2492

Answers (2)

Teshie Ethiopia
Teshie Ethiopia

Reputation: 666

You can pass selected argument to option A as follows.

<select onChange={handleChange}>
    <option value="A" selected>A</option>
    <option value="B">B</option>
    <option value="C">C</option>
    <option value="D">D</option>

</select>

how to use selected when options are mapped using the map function?

You can use selected when options are mapped using map function.

<select
                  className="w-44 px-4 py-2 mt-2 border rounded-md focus:outline-none focus:ring-1 focus:ring-blue-600"
                  value={business_type}
                  onChange={(e) => setBusinessType(e.target.value)}
                >
                  <option value="1" selected="selected">
                    Business Type
                  </option>
                  {data?.businessTypeList?.map((x, y) => (
                    <option>{x.businessType}</option>
                  ))}
                </select>

You can replace Business Type with your own placeholder and map your array object with a single option so that your array instances will get displayed accordingly.

Happy coding.

Upvotes: 0

Vadim
Vadim

Reputation: 170

You can use defaultValue for your purpose

<select defaultValue="A" onChange={handleChange}>

Upvotes: 2

Related Questions