Home > other >  When passing a React functional Component as a parameter of a function, how should I declare the fun
When passing a React functional Component as a parameter of a function, how should I declare the fun

Time:11-03

I have a issue with type declaration for function parameters. Please see the code below,

const FunctionalComponent = ({propA,propB}: FunctionalComponentProps): JSX.Element => {
   return 
}

Now I want to pass the FunctionalComponent as a parameter to another function. How should I declare the parameter type?

const Foo = (
   para1: string,
   TheFunctionalComponent: ??? // Tried React.FC<any>, it work, want to provide more strict such as React.FC<FunctionalComponentProps>, this way it does not work. Is the React.FC<any> the only way? 
)

CodePudding user response:

Consider this example:

import React, { FC } from 'react'

export interface ChildComponentProps {
  name: string;
  id: string;
}

export const ChildComponent = ({ name, id }: ChildComponentProps): JSX.Element => (
  <div>
    Hi {name} my id is {id}
  </div>
);


const ParentComponent: FC<{ Comp: FC<ChildComponentProps> }> = ({ Comp }) =>
  <Comp name={"2"} id={"3"} />

const App = <ParentComponent Comp={ChildComponent} />

Playground

You should also provide a type of your ParentComponent

UPDATE

import React, { FC } from 'react'

export interface ChildComponentProps {
  name: string;
  id: string;
}

export const ChildComponent = ({ name, id }: ChildComponentProps): JSX.Element => (
  <div>
    Hi {name} my id is {id}
  </div>
);


const ParentComponent = (Comp: FC<ChildComponentProps>) =>
  <Comp name={"2"} id={"3"} />

const App = ParentComponent(ChildComponent)

Playground

More generic approach:

import React, { FC } from 'react'

export interface ChildComponentProps {
  name: string;
  id: string;
}

export const ChildComponent = ({ name, id }: ChildComponentProps): JSX.Element => (
  <div>
    Hi {name} my id is {id}
  </div>
);


const ParentComponent = <Props,>(Comp: FC<Props>) =>
  (props: Props) => <Comp {...props} />

const App = ParentComponent(ChildComponent)({ name: 'John', id: '#1' })

Playground

  • Related