reactjstypescriptreact-typescript

Create component through props in React


I have a component SomeComponent which takes a Component or IntrinsicElement through the component property and should construct that component. But this is giving type errors.

Parsing error: '>' expected.eslint

'Component' refers to a value, but is being used as a type here. Did you mean 'typeof Component'?ts(2749)

type Component = /unresolved/ any

Here is my source code and how I want it to be used:

import type { ElementType } from 'react';

function SomeComponent({ component: Component }: { component: ElementType }) {
  return (<Component />);
}

//
// This is how I want SomeComponent to be used:
//

const usage1 = <SomeComponent component="div" />;

function MyComponent() {
  return 123;
}

const usage2 = <SomeComponent component={MyComponent} />;

What am I doing wrong and how can this fixed?


Solution

  • It seems that tsc and/or ESLint treats <Component /> as a TypeScript type assertion (hence it expects > closing angle bracket, instead of the /> self closing tag end), instead of JSX syntax.

    Make sure that these tools treat your code as JSX-enabled, usually with .tsx file extension.