A very common mistake jQuery developers make when starting to write React is to want to bring in jQuery in React. This is usually the case for DOM manipulation. In this post I will show two ways to perform DOM manipulation in React without bringing in jQuery. Ideally, DOM manipulation should be a last resort when writing React code; leave the DOM manipulation up to the React engine and use state/props whenever possible.
There are a few valid reasons for manual DOM maniuplation according to the docs:
- Managing focus, text selection, or media playback.
- Triggering imperative animations.
- Integrating with third-party DOM libraries.
But What Do I Lose By Using JQuery? 🤔
You don’t really lose anything. However, there are at least 2 setbacks:
- extra network overhead to load your front-end
- developer frustration
If experienced React developers look at React components that have any jQuery code in them, it’s usually a huge code smell.
DOM Manipulation in React
For our example, we’ll build a simple form in our component and attach an
onSubmit handler to alert the typed value to the user.
Doing it using jQuery might look something like this:
However, let’s look at three other simple methods to do this.
1. Ideal React™ way:
As previously mentioned, controlling things like the value of an input should be done through state whenever possible, as React has tons of built-in optimizations for this:
Pretty straight forward. However, the point of this post is for scenarios when it’s not as straight forward as grabbing the value of an input, and what your options are to do manual DOM manipulation, as follows.
document.getElementById to grab the input instead. Pretty simple!
3. React Refs
React comes built in with a method to refer to components called Refs (short for references). It is quite simple to use: attach a
ref attribute to the component you want to refer to (in this case our input), and you can refer to it within your main component using