I am working on a React project and need to simulate the hover state on a button without user interaction. Our design system defines certain styles within pseudo-classes, such as hover, and I would like to apply these styles programmatically for demonstration purposes in an environment like Storybook.
Problem: I want to activate the :hover
pseudo-class on React components (specifically buttons) so that they display the hover effect as if the user were hovering over them with their mouse. These styles are defined within our theme, and I cannot directly alter this definition.
Question: Is there any way to programmatically activate pseudo-classes such as :hover
, :active
, :focus
, etc., in JavaScript or React? If so, how can this be done without modifying the original definitions of the pseudo-classes in CSS?
What I’ve Tried: I attempted to use mouse events like mouseover through dispatchEvent, but this did not work.
const buttonRef = useRef(null);
useEffect(() => {
const button = buttonRef.current;
const event = new MouseEvent('mouseover', {
view: window,
bubbles: true,
cancelable: true
});
button.dispatchEvent(event);
}, []);
I aim to force the hover state on multiple buttons simultaneously, such that they remain with the hover style applied until I deactivate it.
Thanks in advance for your time! 🙂