Home > other >  Showing Upcoming Select Options with logic to Previous Selected Select Field
Showing Upcoming Select Options with logic to Previous Selected Select Field

Time:03-29

I'm receiving the data from api like cites nested into state objects

Example:

const data = [
  {
    id: 1,
    name: 'State One',
    cities: [
      {
        id: 1,
        state: 'State One',
        name: 'City One'
      },
      {
        id: 2,
        state: 'State One',
        name: 'City Two'
      },
      {
        id: 3,
        state: 'State One',
        name: 'City Three'
      }
    ]
  },
  {
    id: 2,
    name: 'State 2',
    cities: [
      {
        id: 4,
        state: 'State 2',
        name: 'City 5'
      }
    ]
  }
]

I have to give the Select options of the Cities according to Parent State. Lets say User selected State One in State Select Field then There should be only cities options of the State One in next City Field I can I configure.

Currently; I have created hollow structure of the Select Input Fields but can't find anything how can I configure it. I need little help or any idea to start with.

This is current code;

<Col lg="6" md="12" className="mb-1">
<Label className="form-label  py-1" for="state">
    State
</Label>{' '}
<Row></Row>
<Select
    id="state"
    options={stateOptions}
    defaultValue={stateOptions[0]}
    onChange={(choice) => console.log(choice.value)}
/>
</Col>
<Col lg="6" md="12" className="mb-1">
<Label className="form-label  py-1" for="city">
    City
</Label>{' '}
<Row></Row>
<Select
    id="city"
    classNamePrefix="select"
    options={cityOptions}
    onChange={(choice) => console.log(choice.value)}
/>
</Col>

I have seen some articles but they suggst to use npm libraries but I can't use them because data is a lot different that I want to handle.

CodePudding user response:

You can keep track of the currently selected state and update the cities that the second Select takes.

Also added some comments to explain what the functions are doing.

export default function App() {
  const [state, setState] = useState(null);
  const [city, setCity] = useState(null);

  const onStateChange = (option) => {
    setState(option);

    // to remove city if a different state is selected
    if (!option || option?.value !== state?.value) setCity(null);
  };

  const onCityChange = (option) => {
    setCity(option);
  };

  // a separate useState for cities is not needed
  // as cities depend on the selected state, it can be determined when state changes
  const cities = useMemo(() => {
    if (!state) return [];
    return getOptions(data.find((el) => el.id === state.value).cities);
  }, [state]);

  return (
    <div>
      <Select options={states} value={state} onChange={onStateChange} />
      <hr />
      <Select options={cities} value={city} onChange={onCityChange} />
    </div>
  );
}

Edit codesandboxer-example (forked)

  • Related