nicolabosco87
10/25/2018 - 2:50 PM

HOC + TS -> Edit component props

Higher Order Components tipicizzato.

https://codesandbox.io/s/vvol4m3x37

import * as React from "react";
import Person from "./index.tsx";

interface Props<T> {
  list: T[];
  field: keyof T;
  value: T[keyof T];
}

// P is the "Component to Enhance" Props
// T is the "filter Component" Props (in this example it will be Person)
\!h const filter = <P extends object, T>(Component: React.ComponentType<P>): React.SFC<P & Props<T>> 
=> ({ list, field, value }: Props<T>) => {
  list = list.filter(item => item[field] === value); // Change the list used in "Component" new props
  return <Component list={list} />; // Rendering the "Component to Enhance" with the edited new props
};

export default filter;
import * as React from "react";
import { render } from "react-dom";
import withFilter from "./Filter.tsx";
import List from "./List.tsx";

export interface Person {
  name: string;
  surname: string;
  age: number;
}

const ListWithFilter = withFilter<List, Person>(List);

const elements: Person[] = [
  {
    name: "Paolo",
    surname: "Rossi",
    age: 15
  },
  {
    name: "Ginevra",
    surname: "Bianchi",
    age: 20
  },
  {
    name: "Ilaria",
    surname: "Verdi",
    age: 18
  }
];

const App = () => (
  <div>
\!h    <ListWithFilter field="name" value="Ilaria" list={elements} />
  </div>
);

render(<App />, document.getElementById("root"));
import * as React from "react";
import Person from "./index.tsx";

interface Props<T> {
  list: T[];
}

export default ({ list }: Props<Person>) => (
  <ul>
    {list.map((item: Person) => (
      <li key={item.name}>
        {item.name} {item.surname} ({item.age})
      </li>
    ))}
  </ul>
);