Press "Enter" to skip to content

Sorting elements in React application? It is super easy than I thought.

Sharing is caring!

Sorting is one of most needed feature, if your application has some sort of user interaction with bunch of items or lists.

There are lots of libraries are based on some parent (and a complicated) library but, most of them suck and produce unwanted bugs making things complicated than necessary.

Below is one implementation on how to make your items in your state sort-able.

First of all, let’s assume. you have a state like

In your render function you might be rendering it as:

JSX rocks here to keep things simple.

That was the hard part.

Now, let’s get this done.

We need to pull one library.

This library is what we will use. It is not dependent upon jQuery.

So, we need to dive a bit in JavaScript.

lets import this library in our file.

Inside componentDidMount function of your class, we will add this.

At this point, your lists should be sort-able.

But, we are not done yet.

The remaining task for us is to make a sort function that would reflect the changes on state as well i.e. shift the position.

So, we will be using this neat function for fixing our companies in state.

So, when the event ends, this sort function will take care of sorting your values in state too.

And, we are done.

If you want to see live demo, you can take a look at here.

Everything is awesome.


Be First to Comment

    Leave a Reply

    Your email address will not be published.