Generic component with default type
Asked Answered
H

2

8

In a TSX file, a generic component can be defined:

const MyComponent = <A,>() => <p>my component</p>

Note the , after A.

Now if I want A to be string by default, one would naturally assume that the above should be written:

const MyComponent = <A=string,>() => <p>my component</p>

Except this does not work.

What am I missing?

Hopeh answered 15/11, 2020 at 18:21 Comment(1)
Generics and JSX don't play all that well together. Using <A,> (or e.g. <A extends any>) rather than <A> resolves a parsing ambiguity, but the =string apparently looks enough like a prop to confuse it again.Plasma
A
7

The best solution I could find was to define it as a normal function instead:

const MyComponent = function <A = string>() {
  return <p>my component</p>;
};

While this is not functionally the same as an arrow function, my guess is that in the context of React, you probably won't care most of the time anyway.

Agalloch answered 25/3, 2021 at 20:37 Comment(0)
P
-2

How about:

const MyComponent = <string,>() => <p>my component</p>?

Any reason it wouldn't work?

Protective answered 15/11, 2020 at 18:25 Comment(1)
Type parameter name cannot be 'string'.Plasma

© 2022 - 2024 — McMap. All rights reserved.