I am learning React js and want know that, it is possible to add click handler through reference of component.
I tried following but it didn't work
import React, { Component } from 'react'
export default class RefsDemo extends Component {
constructor(props) {
super(props)
this.inputRef=React.createRef();
this.buttonRef=React.createRef();
}
componentDidMount()
{
console.log(this.buttonRef);
this.buttonRef.current.onClick=()=>this.abchandle()
}
abchandle()
{
alert('hi');
}
render() {
return (
<div>
<button ref={this.buttonRef} >click</button>
</div>
)
}
}
this.buttonRef.current
is a DOM node, not a react component, so to define the on click handler, you should define the onclick
(note the lower case c
) instead:
this.buttonRef.current.onclick=()=>this.abchandle()
https://codepen.io/liboul/pen/jRJmqZ
I believe we need to pick the node using ref and then add an event listner like this -:
We need to import 'react-dom' to make it work
import ReactDOM from 'react-dom'
Then add this piece of code -:
componentDidMount()
{
let domNode = ReactDOM.findDOMNode(this.buttonRef.current);
if(domNode) {
domNode.addEventListener('click', () => console.log('click'));
}
}
Hope it helps.... BTW why do we need to attach click handler when we can do something like this in the JSX
<button onClick={() => console.log('click')} >Click</button>
Can see this
https://stackblitz.com/edit/react-zakgqb?file=Hello.js
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