CodeNewbie Community 🌱

Irakli Tchigladze
Irakli Tchigladze

Posted on • Edited on

Set default value for <Select> element in React

Input elements - <input>, <select>, <textarea> and even buttons are very important part of any web application. They allow us to collect user feedback.

Sometimes you want your users to select one of the many available options. Normally, we do this using <select> and a series of <option>elements.

How to set a default value for <select> element in React

This is really simple to do, but difficult to explain in words. But i'll try.

To set the default value for select, simply set the defaultValue attribute of select element to the same value as the value prop of the <option> element. This way, React will know that one of the options is supposed to be the default.

Let's look at an example:

`<select defaultValue="two"

1
2
3
`

In this case, the default value will be 2.

A simpler way to phrase this is that the defaultValue prop allows you to specify which option is going to be the default. Every option has a value as well, so it also allows us to specify the default value.

In React, we store currently selected value in the state. So whenever user selects something, we want to update the selected value.

This is easy to do with functional components. The useState() hook gives you the state variable, as well as the function to update it.

Simply define the onChange prop on the <select> element to update the state variable to user's most recent choice. You can access the current value by using e.target.value, where e is a placeholder that represents synthetic event.

The value of value prop will be stored in the state. From our previous example, it will be either 'one', 'two', or 'three'. It can also be a boolean, number, or any other type of value.

react-select package

Alternatively, you can use react-select, an excellent tool for implementing select feature in React.

It automatically handles change events and updates the state, so you don't have to.

You only have to import a custom <Select> component, and provide it a list of options, formatted as an array of objects. Every object has two properties: label and value.

To specify normal list of options, invoke a custom in your JSX code, and set options prop to this array of objects.

To set a default option, set defaultValue to a single object with the same two properties - label and value.

SimpleFrontEnd has excellent tutorial on how to set default value using react-select component.

react-select is a great way to give users few options and let them select. It has a number of advantages. For example, if you set something as the default option, it doesn't appear in the dropdown list of options. That's logical, because if users want to select the default option, they can choose to not select anything and simply submit their choice.

Top comments (0)