Overview
You will create a React component that allows users to select a sorting option from a dropdown and displays the sorted list accordingly.
Requirement for React Sorting
- 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 sorts and displays the items accordingly.
- The component must be reusable across different parts of the application with various item arrays.
Instructions for React Sorting
- Create a new React component called “SortingComponent”.
- Add a state variable to the component to track the user’s selected sorting option.
- Create a dropdown menu using the “select” element and populate it with two options: “Name” and “Price”.
- Add an event listener to the dropdown menu that updates the state variable when the user selects a new sorting option.
- Write a function that sorts the array of items based on the selected sorting option (i.e. by name or by price).
- Render the sorted list of items using the “map” function.
- 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
- Add a third sorting option to the dropdown menu that sorts the items by their ID.
- 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) => {
setSortingOption(e.target.value);
};
const handleSortDirectionChange = (e) => {
setIsDescending(e.target.checked);
};
const sortItems = (items, option, isDescending) => {
let sortedItems = items.slice();
if (option === "name") {
sortedItems.sort((a, b) => a.name.localeCompare(b.name));
} else if (option === "price") {
sortedItems.sort((a, b) => a.price - b.price);
} else if (option === "id") {
sortedItems.sort((a, b) => a.id - b.id);
}
if (isDescending) {
sortedItems.reverse();
}
return sortedItems;
};
const sortedItems = sortItems(items, sortingOption, isDescending);
return (
<div>
<div>
<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>
</select>
</div>
<div>
<label htmlFor="sort-direction">Sort direction:</label>
<input type="checkbox" id="sort-direction" checked={isDescending} onChange={handleSortDirectionChange} />
<label htmlFor="sort-direction">Descending</label>
</div>
<ul>
{sortedItems.map((item) => (
<li key={item.id}>
{item.name} - ${item.price}
</li>
))}
</ul>
</div>
);
};
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} />
</div>
);
}
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:
- E-commerce websites: Users can sort products based on price, popularity, or customer ratings.
- Social media platforms: You can use sorting to sort posts based on recency or engagement.
- Music streaming services: You can sort songs based on popularity or release date.
- Task management applications: You can sort tasks based on due date, priority, or status.
- Contact management applications: You can use sorting to organize contacts based on name, company, or job title.
- File manager applications: You can sort files based on name, date modified, or file size.
- Fitness tracking applications: You can use sorting to organize workout data by date, type, or duration.
- Recipe websites: You can sort recipes based on ingredients, cooking time, or rating.
These are just a few examples of applications that use sorting.. Any application that deals with data that needs to be organized in a specific order can benefit from sorting functionality.
Conclusion
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. Moreover, 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. Moreover, 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. Furthermore, keep practising and experimenting with React, and you’ll be well on your way to becoming a skilled React developer!
Boost your React skills with 25 React JavaScript Practice Exercises with Solutions hands-on challenges to master components, hooks, and more!