skip to Main Content
import "./styles.css";
import React, { useState } from "react";
export default function App() {
  const statesAndCities = [
    { state: "Telangana", cities: ["Hyderabad", "Warangal"] },
    { state: "Madhya Pradesh", cities: ["Gwalior", "Bhopal"] },
    { state: "Rajasthan", cities: ["Jaipur", "Jaipur City"] },
    { state: "Chattisgarh", cities: ["Raipur", "ABC"] }
  ];
  const [value, setvalue] = useState([]);
  const [city, setcity] = useState([]);

  const handleChange = (e) => {
    setvalue(e.target.value);
    setcity(statesAndCities.find((state) => state === e.target.value));
    console.log(e.target.value);
  };

  return (
    <div className="App">
      <select onChange={handleChange}>
        {statesAndCities.map((elem) => {
          return <option value={elem.state}>{elem.state}</option>;
        })}
      </select>
      <select onChange={handleChange}>
        {statesAndCities.map((elem) => {
          return <option value={elem.cities}>{elem.cities}</option>;
        })}
      </select>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

How we can filter cities on the bases of state selected in React. What logic do I need to write in handle change for display cities on the basis of states selected

2

Answers


  1. You can try to do it this way:

      const [firstSelectValue, setFirstSelectValue] = useState('');
      const [cities, setCities] = useState([]);
    
      const handleChange = (e) => {
        setFirstSelectValue(e.target.value);
        const selectedState = statesAndCities.find(el => el.state === e.target.value);
        setCities(selectedState.cities)
      };
    

    And in your second select you can map through these cities:

      <select onChange={citiesOnChange}>
            {cities.length > 0 && cities.map((city) => 
              <option value={city}>{city}</option>;
            )}
      </select>
    

    You will also need to make state for your second select as well as a function for handling changes for this select (e.g. citiesOnChange). Additionaly, you should disable the second select if the user didn’t choose the value from the first select.

    Login or Signup to reply.
  2. You would need state, cities and selectedCity. cities will change whenever the user selects a different state. selectedCity will change whenever user selects a different city from cities state, but also whenever the user changes state for a better UI/UX design.

    Here’s how you can go about it:
    Edit infallible-sea-nqy5s9

    import "./styles.css";
    import React, { useState } from "react";
    export default function App() {
      const statesAndCities = [
        { state: "Telangana", cities: ["Hyderabad", "Warangal"] },
        { state: "Madhya Pradesh", cities: ["Gwalior", "Bhopal"] },
        { state: "Rajasthan", cities: ["Jaipur", "Jaipur City"] },
        { state: "Chattisgarh", cities: ["Raipur", "ABC"] }
      ];
    
      const [state, setState] = useState(statesAndCities[0].state);
      const [cities, setCities] = useState(statesAndCities[0].cities);
      const [selectedCity, setSelectedCity] = useState(cities[0]);
      console.log(
        "state:", state,
        "& cities:", cities,
        "& selectedCity:", selectedCity
      );
    
      const handleStateChange = (e) => {
        setState(e.target.value);
    
        // Find "cities" that belong to the selected "state"
        const matchingCities = statesAndCities.find((item) => {
          return item.state === e.target.value;
        });
        setCities(matchingCities.cities);
    
        // When we change state, also change the selectedCity
        setSelectedCity(matchingCities.cities[0]);
      };
    
      const handleCityChange = (e) => {
        setSelectedCity(e.target.value);
      };
    
      return (
        <div className="App">
          <select onChange={handleStateChange}>
            {statesAndCities.map((elem) => {
              return (
                <option key={elem.state} value={elem.state}>
                  {elem.state}
                </option>
              );
            })}
          </select>
          <select onChange={handleCityChange}>
            {cities.map((city) => {
              return (
                <option key={city} value={city}>
                  {city}
                </option>
              );
            })}
          </select>
          <h2>Selected city: {selectedCity}</h2>
        </div>
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search