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

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay