Home > Enterprise >  How do I type a placeholder React element in another Component in TypeScript?
How do I type a placeholder React element in another Component in TypeScript?

Time:04-15

I'm having trouble trying to figure out this Typescript error. Here's the code:

interface AppProps {
  Component: JSX.ElementClass;
  pageProps: JSX.ElementAttributesProperty;
}

const App = ({ Component, pageProps }: AppProps) => {
  console.log(Component)
  console.log(pageProps)
  return (
    <>
    {globalStyles}
    <Component {...pageProps} />
  </>)
}

I get the charming error: JSX element type 'Component' does not have any construct or call signatures. against the 3rd to last line.

My guess is that it is because I'm using <Component ... directly as JSX? And it isn't a real type, i.e. it's just the parameter name being used as a stand in for whatever JSX component is actually being handed in? Is it children somehow? In the code I'm actually using a React Fragment to include <EmotionGlobal/> and <Home/> elements.

CodePudding user response:

PLease, take a look here:

interface AppProps<P> {
  Component: React.JSXElementConstructor<P>;
  pageProps: P;
}

const App = ({ Component, pageProps }: AppProps<{ data: string }>) => {
  console.log(Component);
  console.log(pageProps);
  return (
    <>
      <Component {...pageProps} />
    </>
  );
};

export default App;

Some explanations:

  • Change Component to the proper type - JSXElementConstructor<P> where P is the type of props you need
  • Make interface AppProps generic
  • Type pageProps with generic type P
  • Related