Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 433
Carl Rippon Avatar asked May 25 '18 13:05

Carl Rippon


2 Answers

The event is called click, not onClick.

like image 172
xehpuk Avatar answered Oct 13 '22 12:10

xehpuk


You don't need to use an eventListener to do it. In ReactJS, you can use a handler to the button, like this:

import React, { Component } from "react";

class App extends Component {
  constructor(props) {
    super(props);
  }
  btnHandler = e => {
      console.log("onClick",e)
  }
  render() {
    return <button onClick={this.btnHandler}> click me </button>
  }
} 

export default App;

Take a look at the ReactJS Handling Events docs.

like image 44
reisdev Avatar answered Oct 13 '22 10:10

reisdev