Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

446
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda