SolidJSS
SolidJS4mo ago
3 replies
FatFreeButter

Idiomatic way to dynamically create HTML select options

I have a form page that has only two HTML
select
elements: one for states and another for cities.

On app load, I am using createResource(...) to make a fetch to my back end server to retrieve a nested list of states where each state has a list of cities.

I would like for the city
select
element to start off empty. The user must first select an option from the state
select
element. Then the city
select
element is dynamically populated with results from the createResource(...) call.

For populating the state
select
element, I thought about doing this

<select
  id="state"
  value={selectedState()}
  onChange={(e) => setSelectedState(e.target.value)}
>
  <option value="">Select Option</option>
  {data().states.map((state) => (
    <option value={state.name}>{state.name}</option>
  ))}
</select>


And for populating the city
select
element, this is what I have

<Show when={selectedState()}>
  <select id="city">
    <option value=""Select Option</option>
    {data().states
      .find((s) => s.name === selectedState())
      ?.cities.map((city) => (
        <option value={city.id}>{city.name}</option>
      ))}
  </select>
</Show>


I'm relatively new to Solid.js and was wondering what are the most idiomatic and performant ways to accomplish my goals.
Was this page helpful?