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

153
Vistas
setFunction of useState won't change OnClick

I have this useState element, but the function doesn't get called onClick. I have tried many solutions and debugging and it seems like the Click event doesn't get called, no matter what.

const [modalHotel, setModalHotel] = useState(false)

{modalHotel && <ModalHotel CloseModal = {setModalHotel} />}

<img src="./assets/square.svg" alt="expand" onClick={() => setModalHotel(!modalHotel)}/>

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

0

Sometimes elements won't register onClick events in React unless you specify a tabIndex. Try this:

const checkClick = () => {
  console.log("It worked!!");
  setModalHotel(!modalHotel);
}

<img tabIndex={0} src="./assets/square.svg" alt="expand" onClick={checkClick} />

this will help you to debug whether the click event is actually being fired.

Side Note:

From an accessibility perspective, it's almost always preferrable to use either button or a elements to handle clicks like this. They have tabIndexes by default, and better a11y support in general.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Found the problem!

I had this z-index: -1; in my css, removed it and it worked.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You haven't really provided enough information to completely diagnose your issue. But in the meantime, here is a working snippet with an element that is clickable (a button) to toggle state using a useState hook. You can compare what is different between your non-working code and this working example.

const { useState } = React;

const Thing = (props) => {
  const [modalHotel, setModalHotel] = useState(false);
  return (
    <div>
      <h1>{modalHotel.toString()}</h1>
      <button onClick={() => setModalHotel(!modalHotel)}>Toggle</button>
    </div>
  );
}

ReactDOM.render(
  <Thing />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

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