0

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;

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.