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)}/>
CodePudding user response:
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.
CodePudding user response:
Found the problem!
I had this z-index: -1;
in my css, removed it and it worked.
CodePudding user response:
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>