React Province Disctrict selector

Viewed 49

I want to list the districts of the province selected from the province option. I am pulling from local json file. How can I solve this problem?

<div className="flex items-center px-2">
  <label for="cars">İl Seçiniz:</label>
  <select onChange={(e) => handleProvince(e)}>
    <option key={0} value={0}>
      Lütfen bir İl seçiniz
    </option>
    {Provinces.map((province) => (
      <option key={province.plaka} value={province.il}>
        {province.il}
      </option>
    ))}
  </select>
</div>

<div className="flex items-center px-2">
  <label for="cars">İlçe Seçiniz:</label>
  <select>
    {Provinces.map((item) => (
      <option key={item.plaka} value={item.ilceleri}>
        {item.il === "İstanbul" ? item.ilceleri : null}
      </option>
    ))}
  </select>
</div>

dropdown screenshot
json file

1 Answers

You can achieve this by correctly mapping the districts to the option field as seen in the following CodeSandbox: https://codesandbox.io/s/distracted-rain-s4tnxb?file=/src/App.js

const DATA = [
  {
    province: "Province A",
    districts: ["PA district1", "PA district2"]
  },
  {
    province: "Province B",
    districts: ["PB district1", "PB district2"]
  }
];

export default function App() {
  const [province, setProvince] = useState();
  const [district, setDistrict] = useState();

  const selectProvince = (e) => {
    const selectedProvince = DATA.find(
      (entry) => entry.province === e.target.value
    );
    setDistrict(undefined);
    setProvince(selectedProvince);
  };

  const selectDistrict = (e) => {
    setDistrict(e.target.value);
  };

  return (
    <div className="App">
      <select onChange={selectProvince}>
        {DATA.map((entry, index) => {
          return (
            <option key={index} value={entry.province}>
              {entry.province}
            </option>
          );
        })}
      </select>
      <br></br>
      {!!province && (
        <select onChange={selectDistrict}>
          {province.districts.map((district, index) => {
            return (
              <option value={district} key={index}>
                {district}
              </option>
            );
          })}
        </select>
      )}

      {!!province && (
        <p>
          Selected province {province.province}
          <br></br>
        </p>
      )}
      {!!district && (
        <p>
          Selected district {district}
          <br></br>
        </p>
      )}
    </div>
  );
}
Related