How to manually trigger click event in ReactJS?

HtmlReactjs

Html Problem Overview


How can I manually trigger a click event in ReactJS? When a user clicks on element1, I want to automatically trigger a click on the input tag.

<div className="div-margins logoContainer">
  <div id="element1" className="content" onClick={this.uploadLogoIcon}>
    <div className="logoBlank" />
  </div>
  <input accept="image/*" type="file" className="hide"/>
</div>

Html Solutions


Solution 1 - Html

You could use the ref prop to acquire a reference to the underlying HTMLInputElement object through a callback, store the reference as a class property, then use that reference to later trigger a click from your event handlers using the HTMLElement.click method.

In your render method:

<input ref={input => this.inputElement = input} ... />

In your event handler:

this.inputElement.click();

Full example:

class MyComponent extends React.Component {
  render() {
    return (
      <div onClick={this.handleClick}>
        <input ref={input => this.inputElement = input} />
      </div>
    );
  }

  handleClick = (e) => {
    this.inputElement.click();
  }
}

Note the ES6 arrow function that provides the correct lexical scope for this in the callback. Also note, that the object you acquire this way is an object akin to what you would acquire using document.getElementById, i.e. the actual DOM-node.

Solution 2 - Html

Got the following to work May 2018 with ES6 React Docs as a reference: https://reactjs.org/docs/refs-and-the-dom.html

import React, { Component } from "react";
class AddImage extends Component {
  constructor(props) {
    super(props);
    this.fileUpload = React.createRef();
    this.showFileUpload = this.showFileUpload.bind(this);
  }
  showFileUpload() {
    this.fileUpload.current.click();
  }
  render() {
    return (
      <div className="AddImage">
        <input
          type="file"
          id="my_file"
          style={{ display: "none" }}
          ref={this.fileUpload}
        />
        <input
          type="image"
          src="http://www.graphicssimplified.com/wp-content/uploads/2015/04/upload-cloud.png"
          width="30px"
          onClick={this.showFileUpload}
        />
      </div>
    );
  }
}
export default AddImage;

Solution 3 - Html

Here is the Hooks solution

    import React, {useRef} from 'react';

    const MyComponent = () =>{

    const myRefname= useRef(null);

    const handleClick = () => {
        myRefname.current.focus();
     }

    return (
      <div onClick={handleClick}>
        <input ref={myRefname}/>
      </div>
     );
    }

Solution 4 - Html

You can use ref callback which will return the node. Call click() on that node to do a programmatic click.

Getting the div node

clickDiv(el) {
  el.click()
}

Setting a ref to the div node

<div 
  id="element1"
  className="content"
  ref={this.clickDiv}
  onClick={this.uploadLogoIcon}
>

Check the fiddle

https://jsfiddle.net/pranesh_ravi/5skk51ap/1/

Hope it helps!

Solution 5 - Html

In a functional component this principle also works, it's just a slightly different syntax and way of thinking.

const UploadsWindow = () => {
  // will hold a reference for our real input file
  let inputFile = '';

  // function to trigger our input file click
  const uploadClick = e => {
    e.preventDefault();
    inputFile.click();
    return false;
  };

  return (
    <>
      <input
        type="file"
        name="fileUpload"
        ref={input => {
          // assigns a reference so we can trigger it later
          inputFile = input;
        }}
        multiple
      />

      <a href="#" className="btn" onClick={uploadClick}>
        Add or Drag Attachments Here
      </a>
    </>
  )

}

Solution 6 - Html

Riffing on Aaron Hakala's answer with useRef inspired by this answer https://stackoverflow.com/a/54316368/3893510

const myRef = useRef(null);

  const clickElement = (ref) => {
    ref.current.dispatchEvent(
      new MouseEvent('click', {
        view: window,
        bubbles: true,
        cancelable: true,
        buttons: 1,
      }),
    );
  };

And your JSX:

<button onClick={() => clickElement(myRef)}>Click<button/>
<input ref={myRef}>

Solution 7 - Html

Using React Hooks and the useRef hook.

import React, { useRef } from 'react';

const MyComponent = () => {
    const myInput = useRef(null);

    const clickElement = () => {
        // To simulate a user focusing an input you should use the
        // built in .focus() method.
        myInput.current?.focus();

        // To simulate a click on a button you can use the .click()
        // method.
        // myInput.current?.click();
    }

    return (
        <div>
            <button onClick={clickElement}>
                Trigger click inside input
            </button>
            <input ref={myInput} />
        </div>
    );
}

Solution 8 - Html

Try this and let me know if it does not work on your end:

<input type="checkbox" name='agree' ref={input => this.inputElement = input}/>
<div onClick={() => this.inputElement.click()}>Click</div>

Clicking on the div should simulate a click on the input element

Solution 9 - Html

If it doesn't work in the latest version of reactjs, try using innerRef

class MyComponent extends React.Component {


  render() {
    return (
      <div onClick={this.handleClick}>
        <input innerRef={input => this.inputElement = input} />
      </div>
    );
  }

  handleClick = (e) => {
    this.inputElement.click();
  }
}

Solution 10 - Html

  imagePicker(){
        this.refs.fileUploader.click();
        this.setState({
            imagePicker: true
        })
    }

  <div onClick={this.imagePicker.bind(this)} >
  <input type='file'  style={{display: 'none'}}  ref="fileUploader" onChange={this.imageOnChange} /> 
  </div>

This work for me

Solution 11 - Html

  let timer;
  let isDoubleClick = false;

  const handleClick = () => {
    if(!isDoubleClick) {
      isDoubleClick = true;
      timer = setTimeout(() => {
        isDoubleClick = false;
        props.onClick();
      }, 200);
    } else {
      clearTimeout(timer);
      props.onDoubleClick();
    }
  }

return <div onClick={handleClick}></div>

Solution 12 - Html

this.buttonRef.current.click();

Solution 13 - Html

for typescript you could use this code to avoid getting type error

import React, { useRef } from 'react';

const MyComponent = () => {
    const fileRef = useRef<HTMLInputElement>(null);

    const handleClick = () => {
      fileRef.current?.focus();
    }

    return (
        <div>
            <button onClick={handleClick}>
                Trigger click inside input
            </button>
            <input ref={fileRef} />
        </div>
    );
}

Solution 14 - Html

How about just plain old js ? example:

autoClick = () => {
 if (something === something) {
    var link = document.getElementById('dashboard-link');
    link.click();
  }
};
  ......      
var clickIt = this.autoClick();            
return (
  <div>
     <Link id="dashboard-link" to={'/dashboard'}>Dashboard</Link>
  </div>
);

   

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMamata HegdeView Question on Stackoverflow
Solution 1 - HtmlJohn WeiszView Answer on Stackoverflow
Solution 2 - HtmlSir Codes AlotView Answer on Stackoverflow
Solution 3 - HtmlSajad SaderiView Answer on Stackoverflow
Solution 4 - HtmlPranesh RaviView Answer on Stackoverflow
Solution 5 - HtmlImmutable BrickView Answer on Stackoverflow
Solution 6 - HtmlJack BridgerView Answer on Stackoverflow
Solution 7 - HtmlAaron HakalaView Answer on Stackoverflow
Solution 8 - HtmlAlex OleksiiukView Answer on Stackoverflow
Solution 9 - HtmlmXalnView Answer on Stackoverflow
Solution 10 - HtmlarslanView Answer on Stackoverflow
Solution 11 - HtmlMatt EView Answer on Stackoverflow
Solution 12 - HtmlHadi Abou HamzehView Answer on Stackoverflow
Solution 13 - HtmlSaeed NasiriView Answer on Stackoverflow
Solution 14 - HtmltaggartJView Answer on Stackoverflow