InsightsTopicsContact
Eckher
Your guide to what's next.
Eckher
Insights
Topics
Home › Eckher Insights › <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>
)
Cover
See also
Scroll chaining, overscroll glow, and rubberbanding explained
An overview of the scroll-related behaviors and ways to control them using the overscroll-behavior CSS property.
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?
Creating a playlist in React
How to create a playlist in React?
CSS variables
Using CSS variables.
Eckher
Your guide to what's next.
Copyright © 2021 Eckher. Various trademarks held by their respective owners.