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.
The event is called click
, not onClick
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With