...
/Refactoring the Sorters Component
Refactoring the Sorters Component
Learn how to refactor a React sorting component from a parent-child pattern into an internal state management pattern.
The current Sorters
component
Let’s take a look at the current Sorters
component below:
Press + to interact
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><selectid="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