Search code examples
javascriptreactjsweb-component

addEventListener in a React app isn't working


Some background: I'm trying to consume a custom web component in a react app and trying to listen to events from the web component. I believe you can't just handle the events in the usual react way on custom web component.

i.e.

<custom-button onClick={this.clickHandler}></custom-button>.  

I have tried this and it didn't work.

The problem: So, I'm trying to listen to an event via addEventListener as you would do in vanilla js but the event handler is never getting called.

An example of this is below. I know <button/> isn't a custom web component but it demonstrates the problem:

import React, { Component } from "react";

class App extends Component {
  constructor(props) {
    super(props);
    this.buttonRef = React.createRef();
  }
  componentDidMount() {
    // there are no errors attaching the handler
    this.buttonRef.current.addEventListener("onClick", e => {
      // this point is never reached
      debugger;
      console.log("onClick", e);
    });
  }
  render() {
    return <button ref={this.buttonRef}>click me</button>;
  }
}

export default App;

Any help would be appreciated.


Solution

  • The event is called click, not onClick.