DEV Community

Fatimah
Fatimah

Posted on

React-Select: Pre-select an option with an id only, the easy way.

I recently worked on an application where my colleague was using the React-Select package to manage Select boxes. I was struck by the manner in which a selected option was picked. You had to specify an object like so:

value={{value: optionId, label: optionName}}

For most people, this is really inconvenient because you are most likely getting the id only from the database e.g. pre-selecting the city a company belongs to, from a list of cities and only the cityId is saved in the company object i.e company: {id, name, address, cityId}

Typical ReactSelect component:


export const Select = ({
label, isMulti, options, placeholder, onChange, value
}) => (
<FormGroup className="settings__form-group">
<Label className="form__label" for="name">
{label}
</Label>
<ReactSelect
className="modal-select form__select"
classNamePrefix="modal-select"
isMulti={isMulti}
options={options}
placeholder={placeholder}
onChange={onChange}
value={value}
/>
</FormGroup>
);

My solution was to use the defaultValue and the options to generate the value object:

1: To make things neat, I created a function to generate the value object


const generateValue = (options, defaultValue, isMulti = false) => {
const value = isMulti ? options.filter(option =>
defaultValue.includes(option.value))
: options.find(option => option.value === defaultValue);
return value;
};

2: I assigned this function to the value props of the ReactSelect component.


export const Select = ({
label, isMulti, options, placeholder, onChange, defaultValue
}) => (
<FormGroup className="settings__form-group">
<Label className="form__label" for="name">
{label}
</Label>
<ReactSelect
className="modal-select form__select"
classNamePrefix="modal-select"
isSearchable={false}
isMulti={isMulti}
options={options}
placeholder={placeholder}
onChange={onChange}
styles={selectStyle}
value={options.length ? generateValue(options, defaultValue, isMulti) : '' }
/>
</FormGroup>
);

Viola!!!

Github Gist

Top comments (0)