How to create a React Select - Robin Wieruch

How to create a React Select - Robin Wieruch

A short React tutorial by example for beginners about creating a select in React. First of all, a select is just an HTML select element which can be rendered in React’s JSX:

What may be missing is an associated label to signal the user what value is changed with this select:

In your browser, this select can already change its select state by showing every of its values individually. However, this is just the select’s internal HTML state which isn’t controlled by React yet. Let’s change this by transforming this select from being uncontrolled to controlled :

By using React’s useState Hook and an event handler , we can keep track of the select’s value via React’s state . We can refine this component by rendering the options more dynamically:

A great analogy for this refactoring of the component is the list component in React](/react-list-component/). Next we may want to create a Select component which can be used more than once throughout a React project. Therefore, we will extract it as a new function component and pass the necessary props to it:

Our Select component is a reusable component now. For example, if you would give your select element some CSS style in React , every Select component which is used in your React project would use the same style.

If you would want to create a select group now, you could just use multiple Select components side by side and maybe style them with some border and some alignment, so that a user perceives them as a group of select components:

That’s is it for creating a Select component in React. If you are a beginner in React, I hope this tutorial helped you to understand some concepts and patterns!

Recommended articles