Search⌘ K

Refactoring the Sorters Component

Explore how to refactor the Sorters component to manage its own sorting state and become configurable. Learn to replace props with state variables, add rendering flexibility, and integrate sorting direction for more reusable UI components.

The current Sorters component

Let’s take a look at the current Sorters component below:

TypeScript 3.3.4
import * as React from 'react';
export interface ISortersProps<T> {
object: T;
setSortProperty: (property: keyof T) => void;
}
export function Sorters<T> (props: ISortersProps<T>) {
const { object, setSortProperty } = props;
return (
<>
<label htmlFor="sorters">Sorters - try us too</label>
<select
id="sorters"
onChange={(event) => setSortProperty(event.target.value as any)}
>
{Object.keys(object).map(key => {
return (
<option key={key} value={key}>
Sort by '{key}'!
</option>
)
})}
</select>
</>
)
}

Refactoring steps

Now, let’s make the Sorters component responsible for its own state and sorting. A few steps are required to do this:

  • Remove the object prop, and replace it with a data
...