thevangelist thevangelist - 8 months ago 61
Javascript Question

Programmatically triggering a click

Below an example of triggering a click using jQuery:

$('#input_element').click();


I'm wondering how can I do this in React.js? Are there any best practices?

Answer Source

You don't need jQuery to achieve this. Using vanilla javascript is enough, but there are many ways you can do this:

Vanilla js:

This is probably the preferred way since it's simple and doesn't require additional libraries to be imported (e.g jQuery or React-DOM).

someFunction = () => {
    document.getElementById("input_element").click();
}

jQuery:

If you already have jQuery imported into your project, you could also do:

import jQuery from 'jQuery';
...
someFunction = () => {
    jQuery('#input_element').click();
}

Using ref:

If you'd rather use a ref instead of id you can do:

import ReactDOM = from 'react-dom';
...
someFunction = () => {
  ReactDOM.findDOMNode(this.refs.input_element).click(); 
}