Home > Net >  typescript:'ProtectRoute' cannot be used as a JSX component
typescript:'ProtectRoute' cannot be used as a JSX component

Time:06-15

I use typescript with nextjs, a problem occur as the picture show. When I use a compoment as a JSX element, typescript inform me the infomation: ProtectRoute' cannot be used as a JSX component.

import { PropsWithChildren } from 'react';
type Props = PropsWithChildren<{}>;

export const ProtectRoute = ({ children }: Props) => {
  const { isAuthenticated, isLoading } = useAuth();
  if (
    isLoading ||
    (!isAuthenticated &&
      window.location.pathname !== '/login'
  ) {
    return <div>Loading...</div>;
  }
  return children;
};

import type { AppProps } from 'next/app';
import { AuthProvider, ProtectRoute } from '../contexs/auth';

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <AuthProvider>
      <ProtectRoute>
        <Component {...pageProps} />
      </ProtectRoute>
    </AuthProvider>
  );
}

export default MyApp;

enter image description here

CodePudding user response:

Try to change your ProtectRoute component like this (return a fragment also when the if statements pass through):

import { PropsWithChildren } from 'react';
type Props = PropsWithChildren<{}>;

export const ProtectRoute = ({ children }: Props) => {
  const { isAuthenticated, isLoading } = useAuth();
  if (
    isLoading ||
    (!isAuthenticated &&
      window.location.pathname !== '/login'
  ) {
    return <div>Loading...</div>;
  }
  return <>{children}</>;
};

CodePudding user response:

may be try this


type Props = {
 children: ReactNode;
}

export const ProtectRoute = ({ children }: Props):JSX.Element => {
  const { isAuthenticated, isLoading } = useAuth();
  if (
    isLoading ||
    (!isAuthenticated &&
      window.location.pathname !== '/login'
  ) {
    return <div>Loading...</div>;
  }
  return children;
};

  • Related