jQuery, ReactJS and Higher Order Components

Supposing you just started using ReactJS and you write a component like this:

Wrong Component — a lof of jQuery inside this component

It may work. Is it appropriate ? First of all, we are using a lot of jQuery, probably we don't need it. We can do it in a React way.

First try: Let's move everything to componentDidMount

This is the code you can see at the beginning. Supposing you had this component as a jQuery component, the first thing which came to your mind is this idea: move everything to componentDidMount. But using this we still having a lot of jQuery code, we have just moved to the componentDidMount. Not a big deal.

Second try: Create a function

The other idea you have: Ok, I've heard it's not really cool using jQuery in my React components, let's try to take out some jQuery code. I will create a listener to my window element. And then you have some code like this:

How can I do it better?

Third try: Managing state

Our jQuery is handling something it should not do: state.

React handles state for us very well. This is something we may do when we are using jQuery with React: we tend to imagine things not in the react way, jQuery may help us to do the things in a non-react-way. I'm not really saying you should not use jQuery at all. I'd say, you can do it just using React.

In our component, we are showing a div depending on the scrollTop position. Here scroll is our state.

Supposing your component knows a everything about scroll, what if we would like to re-use the same scroll behaviour for others components?

Fourth try: Creating a Higher Order Component

A higher-order component is just a function that takes an existing component and returns another component that wraps it.

You can read more about it here. The idea is: this component wraps our WrongComponent giving to our WrongComponent a scroll state and some listeners.

Higher Order Component

Right now, you have a HigherOrderComponent and we can re-use this in our last component. Good things here:

  • Reusability
  • Pass arbitrary props to the wrapped component

We are trying to do the things more in a React way which is good. Our code is much better readable, state is managing by React and we can re-use the scroll behaviour in others components.

At a glance:

  • Avoid using jQuery
  • Pay attention on handling state for your React components
  • Try composition when you can, it can probably give you more ideas and can help on reusability
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.