Home > OS >  how to create Dependent dropdown in react
how to create Dependent dropdown in react

Time:06-24

I want to create dependent dropdown using react when i click country it will change and please can explain briefly how we can do

function App() {
  const drop = {
    Country: [
      { CountryName: "India", CountryId: 1 },
      { CountryName: "UK", CountryId: 2 },
      { CountryName: "US", CountryId: 3 },
      { CountryName: "UAE", CountryId: 4 },
    ],
    State: [
      { name: "Delhi", StateId: 1, CountryId: 1 },
      { name: "Punjab", StateId: 2, CountryId: 1 },
      { name: "Chandigarh", StateId: 3, CountryId: 1 },
      { name: "Haryana", StateId: 4, CountryId: 1 },
      { name: "Goa", StateId: 5, CountryId: 1 },
      { name: "Mumbai", StateId: 6, CountryId: 1 },
    ],
  }
  changetostate = (e) => {
    drop({ Countryid: e.target.value });
  }
  return (
    <div>
    </div>
  )
}

export default App;

CodePudding user response:

Here is the simple example for same

import React, { useState } from "react";

function Temp() {
  const drop = {
    Country: [
      { CountryName: "India", CountryId: 1 },
      { CountryName: "UK", CountryId: 2 },
      { CountryName: "US", CountryId: 3 },
      { CountryName: "UAE", CountryId: 4 },
    ],
    State: [
      { name: "Delhi", StateId: 1, CountryId: 1 },
      { name: "Punjab", StateId: 2, CountryId: 1 },
      { name: "Chandigarh", StateId: 3, CountryId: 1 },
      { name: "Haryana", StateId: 4, CountryId: 1 },
      { name: "Goa", StateId: 5, CountryId: 1 },
      { name: "Mumbai", StateId: 6, CountryId: 1 },
    ],
  };

  const [states, setStates] = useState([]);
 const changetostate = (e) => {
    let filterStates = drop.State.filter(
      (item) => item.CountryId === parseInt(e.target.value)
    );

    setStates(filterStates);
  };
  return (
    <>
      Country{" "}
      <select onChange={(e) => changetostate(e)}>
        {drop.Country.map((item) => {
          return (
            <option value={item.CountryId} key={item.CountryId}>
              {item.CountryName}
            </option>
          );
        })}
      </select>
      <div>
        States{" "}
        <select>
          {states.map((item) => {
            return (
              <option value={item.StateId} key={item.StateId}>
                {item.name}
              </option>
            );
          })}
        </select>
      </div>
    </>
  );
}

export default Temp;
  • Related