Search code examples
javascriptcssreactjsfrontendstyled-components

How to render an element when hovering over a disabled button?


I want to render an element when I hover hover a button when it is disabled.

My app component:

import React, { useState } from "react";

function App() {
    const [hover, setHover] = useState(false);
    
    const onHover = () => {
        setHover(true);
    };
    
    const onLeave = () => {
        setHover(false);
    };
    
    
    return (
        <div className="App" style={appStyles}>
            <StyledGlButton
                className = "dis-btn"
                onMouseEnter={onHover}
                onMouseLeave={onLeave}
                disabled = {isDisabled}
            >
                Red
            </StyledGlButton>
            {(hover && isDisabled) && ( 
                <h1>Disabled Button!!</h1>
            )}    
        </div>
    );
}
        
export default App;

and my StyledGlButton:

export const StyledGlButton = styled(GlButton)<GlButtonProps>`
    &.gl-cta {
    font-size: 14px;
    height: 3rem;
    min-height: auto;
    pointer-events: all !important;
}`;

I tried adding pointer-events: all !important; in the css of the button but it is not working.


Solution

  • You can surround the button with span and give that button pointer-events: none, so the span can listen to the events.

    const button = document.querySelector('button');
    const span = document.querySelector('span');
    span.addEventListener('mouseover', (e) => {
      console.log('hovered');
    });
    button {
      pointer-events:none
    }
    <span><button disabled>Button</button></span>