Build dropdown options
Turn rows from an API into the [{ label, value }] list that select and dropdown components take, and read the selection back.
Before you begin
- Install the package. For details, see Get started with Common Utilities.
- Have the rows to show, for example the
dataof a request() result.
Build the options and read the selection
-
Turn the rows into options with
toOptions, naming the keys to use for the label and the value:const rows = [{ id: 7, name: "Acme" }, { id: 8, name: "Beta" }];
const options = helpers(rows, "toOptions", { label: "name", value: "id" });
// [{ label: "Acme", value: 7 }, { label: "Beta", value: 8 }] -
In the change handler, read the new value with
valueFromEvent:const onChange = (e) => setSelected(helpers(e, "valueFromEvent")); -
To show details of the selection, find its option with
findOption:const option = helpers(selected, "findOption", { options }); // { label: "Acme", value: 7 }, or null
findOption matches 7 and "7", because a select often holds its value as text.
valueFromEvent works with a change event, a select's option, or a plain value, and returns true or false for a checkbox.
Shape the options
toOptions takes options that shape the list:
// a label from several keys, joined with " - "
helpers(rows, "toOptions", { label: ["code", "email"], value: "email" }) // label "FF01 - ops@example.com"
// a label from a function
helpers(rows, "toOptions", { label: (r) => `${r.first} ${r.last}`, value: "id" })
// no repeats, sorted by label, with the row's fields kept and an "All" option first
helpers(rows, "toOptions", { label: "name", value: "id", unique: true, sort: true, keepRow: true, includeAll: "All" })
toOptions also accepts plain values and object maps:
helpers(["Air", "Sea"], "toOptions") // [{ label: "Air", value: "Air" }, { label: "Sea", value: "Sea" }]
helpers({ INR: "Rupee" }, "toOptions") // [{ label: "Rupee", value: "INR" }]
For every option and its default, see helpers().