I am building a ReactJS App and I have a function that is called after a click, however I want this click event to be triggered only if the screen width is larger than 1200px.
For example, in the code below I have an onClick
event added to the subContainer
element, I'd like to prevent this onClick
to be triggered if the screen width is smaller than 1200px.
Is there a way to do that without using a listener?
I know I could use a listener and set a condition to determine whether this event would be listened or not; I also know that I could set the condition within the function and prevent the logic to be executed; and I also could create two different JSX elements (one without the event) and render one or another based on my condition. But what I want is to keep the onClick
on the element (without addEventListener
) and prevent it to be triggered
It would be something like that: <div screenWidth > 1200 ? onClick="..." : null>Test</div>
. Of course, this doesn't work.
Is this possible?
P.S. Remember, I am using React, this code is just an example.
const test = () => {
console.log('Test')
}
.subContainer {
width: 100px;
height: 20px;
background-color: red;
color: white;
text-align: center;
cursor: pointer;
}
<div class="container">
<div class="subContainer" onClick="test()">Test<div>
</div>