Search code examples
cssreactjspseudo-element

How to detect if a psudo-element (::after) was clicked in React.js


I am trying to detect click events on an elements ::after pseudo element.

I'm hoping something like this is possible:


//css
div:after{
  content:"X";
  display:block;
}

//jsx
class PsudoExample  extends Component{
  render(){
    return(
    <div onAfterClick={() => {}}>

    </div>
    )
  }
}

Ideally I would like a solution that doesn't involve the use of document.queryselector or something like that.


Solution

  • I don't believe there's a way to distinguish click events from an element and it's pesduo element(s) - the same event handler will fire when the user clicks on either.

    One thing you can do though is use CSS to disable pointer-events on the host element, while allowing pointer-events on the element's pseduo element(s). That would give you a "half-way-there" mechanism for detecting clicks on pseduo element(s) only:

    div:after{
      content:"X";
      display:block;
      pointer-events: initial;
    }
    
    div{
      pointer-events:none;
    }
    

    With that, you would then use the regular onClick handler which should now only fire when the ::after element is clicked:

    class PseudoExample extends Component{
      render(){
        return(
        <div onClick={() => { console.log("after clicked"); }}>
        I host a pseduo elements
        </div>
        )
      }
    }
    

    Hope that helps!