React Sorting - JavaScript Exercise #8

React Sorting - JavaScript Exercise #8

Build a React Sorting Component

Mar 5, 2023ยท

6 min read


In this exercise, you will be building a React component that can sort a list of items based on user selection. The component should allow the user to choose a sorting option from a dropdown menu and then display the sorted list accordingly.


  • The component should receive an array of items as a prop, which it will sort based on the user's selection.

  • The component should have a dropdown menu that allows the user to select a sorting option. The available sorting options should be "Name" and "Price".

  • When the user selects a sorting option, the component should sort the list of items accordingly and display them on the page.

  • The component should be reusable, meaning that it can be used in different parts of your application with different arrays of items.


  1. Create a new React component called "SortingComponent".

  2. Add a state variable to the component to track the user's selected sorting option.

  3. Create a dropdown menu using the "select" element and populate it with two options: "Name" and "Price".

  4. Add an event listener to the dropdown menu that updates the state variable when the user selects a new sorting option.

  5. Write a function that sorts the array of items based on the selected sorting option (i.e. by name or by price).

  6. Render the sorted list of items using the "map" function.

  7. Test your component by passing in different arrays of items and making sure that it sorts them correctly based on the user's selection.

Bonus Requirements

  1. Add a third sorting option to the dropdown menu that sorts the items by their ID.

  2. Add the ability to sort the items in ascending or descending order.

Before you dive into the final output, I want to encourage you to take some time to work through the exercise yourself. I believe that active learning is the most effective way to learn and grow as a developer.

So, grab a pen and paper, fire up your code editor, and get ready to dive into the React Sorting exercise. Once you have completed the exercise, feel free to return to this blog post to compare your solution to mine.

Output for the Sorting exercise

import React, { useState } from "react";

const SortingComponent = ({ items }) => {
  const [sortingOption, setSortingOption] = useState("name");
  const [isDescending, setIsDescending] = useState(false);

  const handleSortingOptionChange = (e) => {

  const handleSortDirectionChange = (e) => {

  const sortItems = (items, option, isDescending) => {
    let sortedItems = items.slice();

    if (option === "name") {
      sortedItems.sort((a, b) =>;
    } else if (option === "price") {
      sortedItems.sort((a, b) => a.price - b.price);
    } else if (option === "id") {
      sortedItems.sort((a, b) => -;

    if (isDescending) {

    return sortedItems;

  const sortedItems = sortItems(items, sortingOption, isDescending);

  return (
        <label htmlFor="sorting-option">Sort by:</label>
        <select id="sorting-option" value={sortingOption} onChange={handleSortingOptionChange}>
          <option value="name">Name</option>
          <option value="price">Price</option>
          <option value="id">ID</option>
        <label htmlFor="sort-direction">Sort direction:</label>
        <input type="checkbox" id="sort-direction" checked={isDescending} onChange={handleSortDirectionChange} />
        <label htmlFor="sort-direction">Descending</label>
        { => (
          <li key={}>
            {} - ${item.price}

export default SortingComponent;

In the code above, we created a SortingComponent that receives an array of items as a prop. The component has a state that tracks the sortingOption selected by the user and another state to track the isDescending sorting direction.

The component has a handleSortingOptionChange function that updates the sortingOption state when the user selects a new sorting option. The handleSortDirectionChange function updates the isDescending state when the user changes the sorting direction.

The sortItems function sorts the items based on the selected sortingOption and the isDescending sorting direction.

Finally, the SortingComponent renders a dropdown menu for the user to select the sorting option, a checkbox for the user to select the sorting direction, and a sorted list of items based on the user's selections.

The bonus features include the ability to sort by ID and to sort in ascending or descending order.

import React from "react";
import SortingComponent from "./SortingComponent";

const items = [
  { id: 1, name: "Product A", price: 9.99 },
  { id: 2, name: "Product B", price: 14.99 },
  { id: 3, name: "Product C", price: 4.99 },
  { id: 4, name: "Product D", price: 19.99 },
  { id: 5, name: "Product E", price: 24.99 },

function App() {
  return (
    <div className="App">
      <SortingComponent items={items} />

export default App;

In the App.js file, we import the SortingComponent and define an array of items that we want to sort. Then, we render the SortingComponent and pass the items array as a prop. Finally, we export the App component.

When we run the app, the SortingComponent will render a dropdown menu, a checkbox, and a sorted list of items based on the user's selection.

Applications where the Sorting component can be used

Sorting can be used in many different types of applications where data needs to be organized in a specific order. Here are a few examples of applications where sorting can be useful:

  1. E-commerce websites: Sorting can be used to sort products based on price, popularity, or customer ratings.

  2. Social media platforms: Sorting can be used to sort posts based on recency or engagement.

  3. Music streaming services: Sorting can be used to sort songs based on popularity or release date.

  4. Task management applications: Sorting can be used to sort tasks based on due date, priority, or status.

  5. Contact management applications: Sorting can be used to sort contacts based on name, company, or job title.

  6. File manager applications: Sorting can be used to sort files based on name, date modified, or file size.

  7. Fitness tracking applications: Sorting can be used to sort workout data based on date, type, or duration.

  8. Recipe websites: Sorting can be used to sort recipes based on ingredients, cooking time, or rating.

These are just a few examples of applications where sorting can be used. Any application that deals with data that needs to be organized in a specific order can benefit from sorting functionality.

Sorting is a fundamental technique in computer science and is used in a wide variety of applications to organize data in a specific order. As a developer, understanding how to implement sorting algorithms and how to incorporate sorting functionality into your applications is an essential skill.

When working on sorting exercises, it's important to keep in mind the different sorting algorithms available and their relative advantages and disadvantages. Additionally, it's crucial to test your sorting implementation with different datasets and edge cases to ensure that it works correctly in all scenarios.

Finally, as you continue to improve your sorting skills, remember to keep learning and experimenting with new techniques and technologies. With dedication and hard work, you can become a proficient sorter and create applications that meet the needs of your users.

Thanks for taking this JavaScript exercise!

I hope you found this exercise helpful and enjoyable, and that it has deepened your understanding of React development. Keep practising and experimenting with React, and you'll be well on your way to becoming a skilled React developer!

If you have any questions or comments, feel free to reach out to me on Twitter(@rajeshtomjoe), or follow me for more updates.

And if you'd like to receive more exercise on JavaScript, be sure to subscribe to my blog.