I am learning React js and want know that, it is possible to add click handler through reference of ponent.
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();
}
ponentDidMount()
{
console.log(this.buttonRef);
this.buttonRef.current.onClick=()=>this.abchandle()
}
abchandle()
{
alert('hi');
}
render() {
return (
<div>
<button ref={this.buttonRef} >click</button>
</div>
)
}
}
I am learning React js and want know that, it is possible to add click handler through reference of ponent.
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();
}
ponentDidMount()
{
console.log(this.buttonRef);
this.buttonRef.current.onClick=()=>this.abchandle()
}
abchandle()
{
alert('hi');
}
render() {
return (
<div>
<button ref={this.buttonRef} >click</button>
</div>
)
}
}
Share
Improve this question
asked Apr 28, 2019 at 11:10
AbhishekAbhishek
2371 gold badge3 silver badges11 bronze badges
1
- Why do you need this? – Jonas Wilms Commented Apr 28, 2019 at 11:29
3 Answers
Reset to default 7this.buttonRef.current
is a DOM node, not a react ponent, 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
What you are trying to do is achievable through the onClick attribute and this is the best practice to implement this task.
so inside the button element just add an onClick attribute like this:
<button onClick={this.abchandle}>click</button>
There is no reason to use add an event listener for this, this is not the react way.
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 -:
ponentDidMount()
{
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./edit/react-zakgqb?file=Hello.js