thevangelist thevangelist - 7 days ago 5
React JSX Question

Programmatically Triggering Click in React.js

How can I do this in React.js? (example in jQuery)

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


Are there any best practices?

Answer

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