...

/

Creating a Generic Sort React Component

Creating a Generic Sort React Component

Build a React component to use with your generic sort function.

Let’s write a generic component that we can use alongside our genericSort function to sort the application’s UI. To do this, we’ll create a new React component called Sorters. We’ll start off by writing some standard HTML5 dropdown markup, using a <select> element.

Press + to interact
import * as React from 'react';
export function Sorters () {
return (
<>
<label htmlFor="sorters">Sorters - try us too</label>
<select
id="sorters">
{/* options here */}
</select>
</>
)
}

One benefit of using generics is that we don’t have to manually create an options dropdown for our widgets, people, or other data types in our application. Instead, we can create React components that generate themselves based on data type alone! To do this, we’ll make the Sorters component generic and pass an instance of whatever object we want to create our dropdown for.

Press + to interact
import * as React from 'react';
export interface ISortersProps<T> {
object: T;
}
export function Sorters (props: ISortersProps<T>) {
return (
<>
<label htmlFor="sorters">Sorters - try us too</label>
<select
id="sorters">
{/* options here */}
</select>
</>
)
}

By using a reference to an object of arbitrary type T, we can leverage Object.keys ...