AI Features

Solution Review: Sorting

Learn how sorting can take place in a react app.

We'll cover the following...

Solution

We will treat the list of data like a table. Each row represents an item of the list and each column represents one property of the item. Headers provide the user more guidance about each column:

const List = ({ list, onRemoveItem }) => (
<div>
<div style={{ display: 'flex' }}>
<span style={{ width: '40%' }}>Title</span>
<span style={{ width: '30%' }}>Author</span>
<span style={{ width: '10%' }}>Comments</span>
<span style={{ width: '10%' }}>Points</span>
<span style={{ width: '10%' }}>Actions</span>
</div>
{list.map(item => (
<Item
key={item.objectID}
item={item}
onRemoveItem={onRemoveItem}
/>
))}
</div>
);

We are using inline style for the most basic layout. To match the layout of the header with the rows, give the rows in the Item component a layout as well:

const Item = ({ item, onRemoveItem }) => (
<div style={{ display: 'flex' }}>
<span style={{ width: '40%' }}>
<a href={item.url}>{item.title}</a>
</span>
<span style={{ width: '30%' }}>{item.author}</span>
<span style={{ width: '10%' }}>{item.num_comments}</span>
<span style={{ width: '10%' }}>{item.points}</span>
<span style={{ width: '10%' }}>
<button type="button" onClick={() => onRemoveItem(item)}>
Dismiss
</button>
</span>
</div>
);

In the ongoing implementation, we will remove the style attributes, because it takes up lots of space and clutters the actual implementation logic (hence extracting it into proper CSS). But I encourage you to keep it for yourself.

The List component will handle the new sort state. This can also be ...