Aryaman Singh
Aryaman Singh's Blog

Aryaman Singh's Blog

Building a sort by list feature in React with Styled Component

Aryaman Singh's photo
Aryaman Singh
·Feb 11, 2022·

3 min read

Building a sort by list feature in React with Styled Component

In this blog we are going to create a sort by feature based on select options in react.

Our goal looks like this:

1.PNG I have used my personal project for reference you can check it out here.

We will be making a functional component DisplayRepositories. Size, Fork, Stars are used for sort by options.

Two react states and data to populate the list are needed to control the behavior of the component:

  1. displayData : It will display the list according to what option the user selects.
  2. selects : It will store what option does user select.
  3. reposData : Array of JSON objects to populate our list.

I have attached a dummy array of JSON objects reposData we will be using to sort our list.

From the JSON objects we will use the value of Size, Fork, Stars for our sort by options.

Setting up our DisplayRepositories component :

You can pass the data through props or consume it through Context API, here I have passed it through props.

const [selects, setSelects] = useState('Size')

We will initialize selects as Size so that on first render we will always have a populated list that is sorted by Size. If we initialize it as null then the list won't be displayed until selects is updated by the user.

changeData function receives an option value that user will select and modify the list accordingly.

const sortedRepos = [...reposData]

We need to create a copy of the reposData object to sortedRepos so that we do not modify the original data whenever the user changes the option.

sortedRepos.sort((a, b) => b.stars - a.stars)

Check the option selected by the user and sort the list accordingly.

if (sortedRepos.length >= 8) sortedRepos.length = 8

Since the list can be very large I have displayed only the top 8 objects. You can display whatever length you want or can skip this if you are dealing with small and fixed sized list.

setDisplayData(sortedRepos)

Lastly update the displayData state that will be used to map over the list.

useEffect(() => {
    changeData(selects)
  }, [selects])

Whenever the selects state value is changed by the user we need to update the DOM of the component. For that we will use the useEffect hook and make sure to put the selects state we want to listen to in useEffect dependencies array.

Below is the screenshot of DisplayRepositories component:

carbon (3).png

Code with styled components.

This is my first blog I hope you like it. Feel free to give suggestions in the comments below. Happy Coding 😊

 
Share this