You have probably heard a lot of comments on React: “React is awesome”, “it’s an awful lot of code to write to achieve the same using jQuery”, etc. It is a lot of code – a lot of useful code, and still pretty fast! Even more useful: overcoming immutability and using the virtual DOM vs. the actual DOM of JQuery. Feel free to check it out here:

virtual-dom-and-real-dom-understanding-the-differences

It is this parallel representation of DOM that makes react applications render faster applying as few DOM mutations as possible using the shouldComponentUpdate lifecycle function.

In addition to the fast rendering, what I find useful with react is the beautiful ecosystem; a fast increasing and myriad of components that ease development using consistent patterns. It does get interesting to see the fast paced migration or adaptation of existing JQuery components to work with react. There are many React-friendly implementations of JQuery: datatables.net or JQuery Chart.js or for that matter many other well-known JQuery components.

JQuery Selectors vs. React Refs
One of the most power features of JQuery is the ability to seamlessly select DOM elements to perform desired actions. This is touted to be far easier than using React. Let us now look at a simple case of targeting DOM elements using Refs in React.

An input element can be targeted using JQuery ID selector as $(“#username”). The same is achieved in React using this.refs.username. Obviously, the element must be attributed using the ref attribute in addition to an id attribute.

This is simple, intuitive and yet powerful. However, it turns out refs like these aren’t always available. For example, refs are not present during the initial render. You must use one of the react’s lifecycle events such as componentDidMount or componentDidUpdate. In addition, it does help to pay attention to a list of cautions in React Documentation:

https://facebook.github.io/react/docs/more-about-refs.html

Specifically – “Never access refs inside of any component’s render method – or while any component’s render method is even running anywhere in the call stack.”

Furthermore, with the release of React v0.14, refs will now return the DOM node itself. There is no need to do this.refs.username.getDOMNode() and it is therefore deprecated.

Refs using Typescript
Before accessing the refs in your typescript code, it is imperative to define the typing for the referenced elements in Typescript. This can be done in your class itself using the following pattern:

refs: {

[string: string]: Element;

username: HTMLInputElement;

}

Conclusion
As much as you love JQuery, it is obvious that elements can be faster referenced in a React way using Refs. I do believe that JQuery still has its uses in React applications, but there are better and perhaps righteous ways to target DOM elements.