Skip to main content

React Select

React-select is a popular standalone component for dropdowns. This shows an example integration.

Warning: opinions! I've used react-select on many projects and like it a lot. Once it's integrated into your app it looks and works intuitively and everyone loves it. But every time I use it I'm struck by the poor API design of having to pass a complex object as the value to the fields. That makes even common things like accommodating localization becomes very complicated since the value needs to change all the time.

This integration highlights that difficult API: we rely on the customProps prop to pass in various things including a custom onChange handler.

But hopefully this'll give you a starting point for configurating your own react-select usage.

Select...
Select...

import React, { useState } from 'react';
import Select from 'react-select';
import { CountryDropdown, RegionDropdown } from 'react-country-region-selector';

const customRender = (props) => {
const {
options,
value,
disabled,
onChange,
onBlur,
customProps,
...selectProps
} = props;

return (
<Select
{...selectProps}
options={options}
isDisabled={disabled}
isSearchable={true}
isClearable={true}
value={customProps.reactSelectValue}
onChange={customProps.onChange}
/>
);
};

type ReactSelectOption = {
label: string;
value: string;
};

const ReactSelect = () => {
const [country, setCountry] = useState<ReactSelectOption | undefined>();
const [region, setRegion] = useState<ReactSelectOption | undefined>();

return (
<>
<div style={{ width: 200, display: 'inline-block', marginRight: 8 }}>
<CountryDropdown
value={country?.value || ''}
className="country"
name="country-field"
customRender={customRender}
customProps={{
reactSelectValue: country,
classNamePrefix: 'country-',
onChange: (value: ReactSelectOption) => {
setCountry(value ? value : undefined);
setRegion(null);
},
}}
/>
</div>
<div style={{ width: 200, display: 'inline-block' }}>
<RegionDropdown
country={country?.value || ''}
value={region?.value || null}
className="region"
name="region-field"
customRender={customRender}
customProps={{
reactSelectValue: region,
classNamePrefix: 'region-',
onChange: (value: ReactSelectOption) => {
setRegion(value ? value : undefined);
},
}}
/>
</div>
</>
);
};

export default ReactSelect;