Titulum
Titulum

Reputation: 11496

React.FunctionComponent with generics in typescript

I'm creating a component that takes an arbitrary list of values and a transformer that will render a specific value. The values can be of any type, as the rendering is handler by the transformer, but the compiler is complaining about the generics parameter.

Here is a minimal example:

interface MyListParams<T> {
  values: T[];
  transformer: (value: T) => JSX.Element
}

export const MyList: React.FunctionComponent<MyListParam<T>> = ({

}) => <>
    {values.map(transformer)}
  </>

This code gives me the error Cannot find name 'T'. in code React.FunctionComponent<MyListParam<T>>.

I do realize that I have to tell typescript that this function is using generics, but I fail to find the correct place to do so.

Upvotes: 0

Views: 964

Answers (2)

Ramesh Reddy
Ramesh Reddy

Reputation: 10662

I don't think there's a way to pass a type to the component when using React.FC, so you can try:

interface MyListParams<T> {
    values: T[];
    transformer: (value: T) => JSX.Element;
}
  
const MyList = <T extends object>(props: PropsWithChildren<MyListParams<T>>) => <></>;

Upvotes: 2

Dennis Vash
Dennis Vash

Reputation: 53994

The generics is on the interface - meaning you want to reuse the interface.

In your example you are using the interface so you need to specify its type:

// T is string
export const MyList: React.FunctionComponent<MyListParams<string>> = ({
values, transformer
}) => <>{values.map(transformer)}</>

If the generics on the function see official examples (not a real use case in function component).

Upvotes: 0

Related Questions