Home > Software design >  How to type a prop which is a function component in react typescript
How to type a prop which is a function component in react typescript

Time:12-29

I have a react component which accepts a react function component as a prop.

My code:

interface ComponentBProps {
  someComponent?: React.ComponentType;
  msg: string;
}

function ComponentB({someComponent: SomeComponent, msg}: ComponentBProps ) {
  return (
    <div>
      {
        SomeComponent && <SomeComponent>
          <div>
            {msg}
          </div>
        </SomeComponent>
      }
    </div>
  );
}

function ComponentA() {
  return (
    <ComponentB
      someComponent={({children}) => <div>{children}</div>}
      msg="msg"
    />
  );
}

It gives me the error

Type '{ children: Element; }' has no properties in common with type 'IntrinsicAttributes'.
<SomeComponent>
  <div>

and

Property 'children' does not exist on type '{}'.
<ComponentB
  someComponent={({children}) => <div>{children}</div>}
  msg="msg"
/>

what type should I assign to

someComponent?: React.ComponentType;

react version: ^18.2.0

CodePudding user response:

The following works if you want to enforce a specific React component.

const ComponentA: React.FC<{ name: string }> = ({ name }) => <div>hello {name}</div>;

interface PropsB {
  component: typeof ComponentA;
}

const ComponentB: React.FC<PropsB> = ({ component: Component }) => (
  <div>
    <Component name='John' />
  </div>
);

<ComponentB component={ComponentA} />;

CodePudding user response:

I like to use FunctionComponent imported from React

type Props = {
   component: FunctionComponent<OtherProps>
}

export function SomeComponent({ component: Component }: Props) {
  return <Component />
}
  • Related