Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Click Handler through reference of component

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>
    )
  }
}
like image 877
Abhishek Avatar asked Oct 17 '25 16:10

Abhishek


2 Answers

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

like image 145
Matthieu Libeer Avatar answered Oct 19 '25 06:10

Matthieu Libeer


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

like image 45
Abhisar Tripathi Avatar answered Oct 19 '25 05:10

Abhisar Tripathi