DEV Community

Fatimah
Fatimah

Posted on

4

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay