Search code examples
reactjstypescriptreact-router-domhigh-order-component

JSX.Element' is not assignable to type 'ReactNode' in React functional HOC


I need to write HOC that will wrap my components into Suspense, I will pass the component and fallback as HOC props.

my hoc:

export const withSuspense = ({ Component, Fallback }: any)=> {

  return (props:any) => {
    return (
      <Suspense fallback={<Fallback />}>
        <Component {...props} />
      </Suspense>
    );
  };
};

Then I need to render in a Route(react-router v 6.15)

  <Route
    path="messages"
    element={withSuspense({MessagesPage,Loader})}
  />

Got an error Type '(props: any) => JSX.Element' is not assignable to type 'ReactNode'.

I tried to define the HOC props as ReactNodes but it didn't work. Any ideas, please?


Solution

  • 'JSX.Element' is not assignable to type 'ReactNode' in React functional HOC

    element in the newest react-router-dom expects a ReactNode, not a function, that returns JSX or ReactNode.

    const Component = withSuspense({ MessagesPage, Loader });
    
    <Route
      path="messages"
      element={<Component />}
    />