Abhishek
Abhishek

Reputation: 237

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>
    )
  }
}

Upvotes: 4

Views: 13108

Answers (3)

Abhisar Tripathi
Abhisar Tripathi

Reputation: 1659

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

Upvotes: 1

ShaiShai
ShaiShai

Reputation: 144

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.

Upvotes: 1

Matthieu Libeer
Matthieu Libeer

Reputation: 2365

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

Upvotes: 7

Related Questions