I can't seem to find anyone with this same issue online with React, unless I've been searching for the wrong thing?
I have a button (anchor tag) that has an onClick
event. When the onClick
event is triggered it calls a loadMore()
function that makes an API call and updates some state.
However on a mobile device (not mobile resolution on desktop!) when I click the button, the onClick
event works and returns what is expected, however it applies a hover state on the button. For the button hover state I have a background color applied
The hover state will stick until I click away anywhere else on the screen. So the background color sticks until I click away.
Now, this isn't exactly desirable. Why is this happening, and how did I prevent it?
Here is my Button
Component
const Button = props => {
const buttonDisabledClass = props.disabled ? "Button--disabled " : "";
const hiddenClass = props.hidden ? "Button--hidden " : "";
const modifierClass = props.modifier ? props.modifier : "";
return (
<>
<a
onClick={!props.disabled ? props.onClick : undefined}
className={
"Button " + buttonDisabledClass + hiddenClass + modifierClass
}
>
{props.children}
{props.buttonText ? (
<span
className={`Button-text ${
props.buttonMobileText ? "Button-desktopText" : ""
}`}
>
{props.buttonText}
</span>
) : null}
{props.buttonMobileText ? (
<span className="Button-mobileText">{props.buttonMobileText}</span>
) : null}
</a>
</>
);
};
Here is the parent component
The parent component imports the Button
component and has the function that makes the API request (just have a simulated one here as an example)
function App() {
const [number, setNumber] = useState(0);
/*simulate http request*/
const ttl = 500;
const loadMore = () => {
const timeout = setTimeout(() => {
setNumber(number + 1);
}, ttl);
return () => {
clearTimeout(timeout);
};
};
return (
<div className="App">
{number}
<Button
key={"loadMoreBtn"}
modifier="Button--loadMore Button--Inline"
onClick={() => loadMore()}
>
Load More
</Button>
</div>
);
}
So, how can I make it so a click on a mobile device does not register hover but still have the hover working on a desktop device as it currently is?
I have a CODESANDBOX if you wish to test it out for yourself
Here is a link for you to test on your mobile device.
The button is orange by default, and grey on hover. On mobile, this is what happens when you click...
Any help would be greatly appreciated!