168

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>
5
  • Looking at some external libraries, it seems a good idea to make the input element programmatically: github.com/okonet/react-dropzone/blob/master/src/index.js#L7 Commented Oct 7, 2016 at 9:26
  • I can't see why you would ever want to do this in React. What are you looking to do? Commented Oct 7, 2016 at 9:37
  • @tobiasandersen It is a perfectly valid use-case to programmatically focus an input element, which is likely what the asker wants to accomplish with the programmatically triggered click. Commented Oct 7, 2016 at 9:49
  • Yeah sure, both focus and blur are perfectly valid. But clicking? The reason I'm asking is that if e.g. focusing is the use case, then it's better to show that. But if click really is the use case, then it's better to just call the handler. Commented Oct 7, 2016 at 9:57
  • @JohnWhite Well it could be bound correctly :) But you're probably right, and it wasn't my meaning to come off snarky. Just wanted to see what the real intention behind this was. Commented Oct 7, 2016 at 10:08

15 Answers 15

176

Update

Since the original answer, React has mostly transitioned to functional components and hooks. The basic principles remain the same, however, only the syntax changes.

First you need to get a reference to your DOM element using the useRef hook:

const inputRef = React.useRef(null);
...
<input ref={inputRef} />

Then you just call click() on that DOM element from an event handler:

inputRef.current?.click() // or .focus() for text fields

Note: inputRef.current will point to an actual DOM element, same as what you would get using document.getElementById or similar, so the same methods and properties are available.

Full example:

function MyComponent() {
  const inputRef = React.useRef(null);
  const handleClick = React.useCallback(() => inputRef.current?.click(), []);

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

Original Answer (class component)

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(); // or .focus() for text fields

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.

Sign up to request clarification or add additional context in comments.

12 Comments

This is not working for me. Not sure if it's out of date, but I successfully assign the element, but when I call click on it, click is undefined. I can see all the other attributes and callbacks that I've assigned to that element. Any ideas?
"Refs no longer return a document DOM node, they return reference to a React virtual DOM node" That's definitely a misconception. Refs don't return "virtual DOM" nodes. Source: I work on React.
@DanAbramov So what's the recommended method for this ?
@JohnWeisz Thank you soooooo much, it worked for me, I had this necessity to handle with click outside of Form because I hade to put some elements between the button and form.
@TheJKFever If you're in TypeScript, click might be undefined because input is of type; HTMLInputElement | null;, therefore use: onClick={() => { if(inputElement) (inputElement).click(); } } to get it to compile!
|
46

Here is the Hooks solution:

import React, {useRef} from 'react';

const MyComponent = () => {
    const myRefname= useRef<HTMLInputElement>(null);
    const handleClick = () => {
        myRefname.current.focus();
     }

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

3 Comments

"myRefname.current.focus is not a function"
@Spoderman4 Just assign a type to the useRef function. For example: const myRef = useRef<HTMLInputElement>(null);
good answer, using myRefname.current.click();
32

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;

2 Comments

This looks like more React Oriented answer.
Use innerRef={this.fileUpload} instead of ref={this.fileUpload} in ReactJS. Rest all code is working file.
10

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!

4 Comments

when you link to a jsfiddle, it's concidered a good practise to put at least the relevant code in here (btw: the snippet editor supports reactjs as well)
It is worth noting that while the string ref approach is not deprecated, it is considered legacy functionality that is superseded by the callback-based syntax: ref={elem => this.elem = elem} -- This is detailed in Refs to Components.
@JohnWhite Valid suggestion. Updated the answer!
Also, you need to check and make sure el isn't null/undefined before you do that.
9

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

}

Comments

8
this.buttonRef.current.click();

2 Comments

this fix my problem, I don't know why people unvote this code
yes, it requires more context about useRef, such we can find in other answers, but that's definitely the answer as of today / 2023
6

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

Comments

5

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

3 Comments

For me this wasn't working as click and focus were not available. But what did work is this answer, stackoverflow.com/a/54316368/3893510 if instead of trying to do myInput.current?.click(); You do: myInput.current.dispatchEvent( new MouseEvent('click', { view: window, bubbles: true, cancelable: true, buttons: 1, }), ); It should work
What is the meaning of ? in myInput.current?.focus();
@JuliodeLeon it is "optional chaining" - introduced recently in JavaScript developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… It's used when you want to access or a call a function on an object that may be undefined.
2

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

Comments

1
  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>

Comments

1

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

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0

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

Comments

0

  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

Comments

0

Radio buttons are a little trickier; you only want to click on first render:

const MyComponent = () => {
   const v1 = useRef(null);
   
    const body =  <div>
       {Object.keys(versions).map((k, i) => (
           <div key={k}>
               <label>
                   <input
                       type="radio"
                       name="viz"
                       value={k}
                       onClick={handler}
                       style={{ width: "1em" }}
                       ref={i === 0 ? v1 : null}
                    ></input>
                        {k}
                </label>
            </div>
        ))}
        </div>
    );

    useEffect(() => {
        v1.current?.click();
    }, []);
    return body;
}

Comments

-3

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

3 Comments

Expectaion is in React
Manipulating the dom directly is discouraged in react and for the right reasons. storing a reference with useRef hook is a much better implementation.
yep I did not say anything about best practice above is the hackey way but it works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.