Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

451
Vistas
How to filter city as per selected state in reactjs?

I have data in dropdown now I want to filter city as per selected state, how can I do this in reactJs?

Giving Error:- enter image description here

API Response:- enter image description here

My code:-

function setSelectedOption(e) {
  console.log(e.target.value);
  let selectedState = e.target.value;
}

function GetEgyptStates() {
  const [egyptData, setEgyptData] = React.useState(null);

  React.useEffect(() => {
    axios
      .get("http://localhost:3000/states-and-districts.json")
      .then((response) => {
        setEgyptData(response.data);
        console.log(response.data)
      });
  }, []);

  if (!egyptData) return null;

  return (
    <div>
      <select onChange={setSelectedOption}>
        <option> -- Select State -- </option>
        {Object.entries(egyptData.Egypt).map(([key, val]) => (
          <option>{key}</option>
        ))}
      </select>

      <select>
        <option> -- Select City -- </option>
        {egyptData.Egypt.selectedState.map((state) => (
          <option>{state}</option>
        ))}
      </select>
    </div>
  );
}

ThankYou for your efforts!

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

I think this code can help you **If you want get property with string name you can use setEgyptData[selectedState]

  function GetEgyptStates() {
    const [egyptData, setEgyptData] = React.useState();
    const [cities,setCities]=React.useState([]);
    const [selState,setselState]=React.useState([]);
    const [selcity,setselcity]=React.useState([]);
    function setSelectedOption(e) {
        console.log(e.target.value);
        let selectedState = e.target.value;
        setselState(selectedState)
        setCities(setEgyptData[selectedState])
      }
    React.useEffect(() => {
      const fetchData=async ()=>{ 
          let response =await axios
        .get("http://localhost:3000/states-and-districts.json");
          setEgyptData(response.data);
    }
    if(!egyptData)
        fetchData();
    }, [egyptData]);
  
    if (!egyptData) return null;
  
    return (
<div>
      <select value={selState} onChange={setSelectedOption}>
        <option> -- Select State -- </option>
        {Object.entries(egyptData.Egypt).map(([key, val]) => (
          <option key={key}>{key}</option>
        ))}
      </select>

      <select value={selcity} onChange={({target})=>setselcity(target.value)}>
        <option> -- Select City -- </option>
        {cities.map((city) => (
          <option key={city}>{city}</option>
        ))}
      </select>
    </div>
    );
  }
about 4 years ago · Juan Pablo Isaza Denunciar

0

Your setSelectedOption function does not set state to update the UI

For the fix,

You should introduce

const [selectedState, setSelectedState] = useState()

And add it to setSelectedOption

function setSelectedOption(e) {
  console.log(e.target.value);
  let selectedState = e.target.value;
  setSelectedState(selectedState)
}

By the way, egyptData.Egypt.selectedState does not exist in your current code too, you should use egyptData.Egypt[selectedState]

{egyptData.Egypt[selectedState].map((state) => (
   <option>{state}</option>
))}
about 4 years ago · Juan Pablo Isaza Denunciar

0

seems egyptData.Egypt.selectedState is undefine like @Bravo said

you can do it like egyptData.Egypt.selectedState && egyptData.Egypt.selectedState.map() or egyptData?.Egypt?.selectedState?.map()

it seems like it renders before data your set method call (useEffect)

instead of doing this if (!egyptData) return null try if (!egyptData) return <></>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda