Eckher
EckherInsightsContact
Eckher
Your guide to what's next.
<select> in React
Oct 7, 2019

<select> in React

How to implement a controlled <select> in React?

This is an example of a controlled <select> implementation in React using the JSX syntax:

import React from 'react';

type Value = any

type SelectProps = {
    options: {
        label: string
        value: Value
    }[]
    value: Value
    onChange: (value: Value) => void
}

const Select = ({ options, value, onChange }: SelectProps) => (
    <select
        onChange={(event: React.ChangeEvent<HTMLSelectElement>) => {
            const selectedIndex = event.target.selectedIndex
            onChange(options[selectedIndex].value)
        }}
        value={value}
    >
        {options.map(({ label, value }) => (
            <option key={value} value={value}>{label}</option>
        ))}
    </select>
)

If the Value type is string, the onChange prop passed to <select> can be simplified:

type SelectProps = {
    options: {
        label: string
        value: string
    }[]
    value: string
    onChange: (value: string) => void
}

const Select = ({ options, value, onChange }: SelectProps) => (
    <select
        onChange={(event: React.ChangeEvent<HTMLSelectElement>) => onChange(event.target.value)}
        value={value}
    >
        {options.map(({ label, value }) => (
            <option key={value} value={value}>{label}</option>
        ))}
    </select>
)
See also
Built-in React hooks
The list of built-in React hooks.
Declaring custom JSX/HTML attributes in TypeScript
How to specify non-standard JSX/HTML attributes in TypeScript?
Multi-<select> in React
How to implement a controlled multi-<select> in React?
Styling native HTML dropdowns
How to style the native HTML dropdown?
Authenticating to an npm registry
How to authenticate to an npm registry?
Creating a JavaScript library with webpack
How to bundle a JavaScript library with webpack?
Loading npm dependencies from multiple registries
How to add npm dependencies from multiple package registries?
CSS variables
Using CSS variables.