How to use Generics with the props of a component?

Asked

Viewed 64 times

1

I’m trying to create a component that will accept a generic type within the props. I’m trying to do it this way:

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

const componente: React.FC<Props<T>> = (props) => {...}

However, this way it returns an error saying that T has not been defined. What would be the correct way to create a component with generic props?

  • 1

    Felipe, I was reading a PR on Github and I ended up remembering this question: https://github.com/facebook/create-react-app/pull/8177

1 answer

2


Just use as a generic of normal functions, Typescript will understand that it is an React component when you call it.

Thus:

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

//                  ↓↓↓
function MyComponent<T>(props: Props<T>) {
  return (
    <>{JSON.stringify(props.items, null, 2)}</>
  );
}

Note that you will not be able to use a Arrow Function using the type React.FC, since the generic would have to come afterward. The guy React.FC adds the property children implicitly. So, if your component has to use that prop, just modify the interface Props:

interface Props<T> {
  items: T[];
  children: React.ReactNode;
}

To define the generic in the component, use this notation:

<MyComponent<string> items={['A', 'B', 'C']} />
<MyComponent<number> items={[1, 2, 3]} />

In the end, you’ll have something like:

import React from 'react';

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

function MyComponent<T>(props: Props<T>) {
  return (
    <>{JSON.stringify(props.items, null, 2)}</>
  );
}

function MainComponent() {
  return (
    <> 
      <MyComponent<string> items={['A', 'B', 'C']} />
      <MyComponent<number> items={[1, 2, 3]} />
    </>
  );
}

See working on Typescript playground.

  • It would be like Mycomponent to be an Arrow Function?

  • 1

    Yeah, but you couldn’t use the type React.FC, since the generic of the component would come afterward of the kind you would pass to the generic of React.FC.

  • @Felipeavelar, some information was missing in the answer?

  • No, no, I wanted to see if anyone else would answer before I said yes, but it looks like there won’t be anyone else :/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.