Create <select> dropdowns and set their default value in React functional components
Every dynamic React application should give users some way to interact with the app. Most commonly we use standard input fields where users can enter anything. In this article, we will explore how to set up dropdowns so users can choose one of many provided options.
How to set default value for <Select> elements in React
You can easily select one of the options by default. This is useful if you need to suggest one of the choices.
First, you need to set up a normal <select> in React. This involves multiple routine steps. Create a state variable and the function to update it. Then tie <select> element’s value to the state variable and set an onChange event handler. Then come up with a few options with unique value values. This may sound strange, but the value is an attribute for <option> element in React and HTML. Developers should set it to a unique value.
Next, simply add the defaultValue attribute to the <select> element to set its default value. You need to specify which option is going to be selected by default. To specify this, simply set defaultValue to the value of one of the options.
You can also set a placeholder as the default option. It will allow you to not use a label. Usually, placeholders look better. Check this guide to see a live demo of <select> default value.
There are a number of libraries that provide custom functionality. Even though you don’t need a custom component to set a default value, you might still need it for other advanced features like multi-select.
These custom components accept options as a prop. You create an array of objects with two properties – label and value. Every object describes one option. Then you set options prop on the select element itself.
When dealing with custom components like these, you can set default values the same way you set options. Use the same attribute defaultValue, but this time you need to set it to an object that describes an option that should be the default.
Generally, I wouldn’t recommend using libraries when you don’t need them. However, sometimes building a certain feature takes too long. Still, you might learn something by building it. I’ve learned a lot by looking at interesting libraries and trying to build their features myself.