Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What's the type of "any" component in React?

I want to define the type of component. It doesn’t matter how many props it receives, is it a class or a function component, I don’t even care if it returns a JSX element or just null or any string.

All I want to say is "a component", which is defined by React as anything that may have a key prop and a ref prop. I tried using React.Component:

  function Ramadan(){
    return <></>
  }

  const templatesMap: { [key: string]: React.Component } = {
    ramadan: Ramadan,
    adha: () => <></>,
    fitir: () => <></>,
    unset: () => <></>,
    mothers: () => <></>,
    birthDay: () => <></>,
  }

but TypeScript is showing the following error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Type '() => Element' is not assignable to type 'Component<{}, {}, any>'.ts(2322)
WriteContent.tsx(10, 25): The expected type comes from this index signature.

>Solution :

You could use React.ComponentType which is typed as:

React.ComponentClass<P, any> | React.FunctionComponent<P>

Example:

function Ramadan(){
  return <></>
}

const templatesMap: { [key: string]: React.ComponentType<any> } = {
  ramadan: Ramadan,
  adha: () => <></>,
  fitir: React.forwardRef((props, ref) => <></>),
  unset: class MyClassComp extends React.Component { 
    render() { return <></> } 
  },
  mothers: () => null,
  birthDay: () => <></>,
}

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading