Home > Net >  Type '0 | Element | undefined' is not assignable to type 'Element'
Type '0 | Element | undefined' is not assignable to type 'Element'

Time:12-21

I am getting an error as:

Type '0 | Element | undefined' is not assignable to type 'Element'. Type 'undefined' is not assignable to type 'ReactElement<any, any>'.ts(2322)

when i do conditional render. how to render by condition here?

export const Home: FC = (): JSX.Element => {
  const [initials, setInitials] = useState<InitialProps[] | null>(null);
  useEffect(() => setInitials(initialInitialPropsSchema), []);
  return initials?.length && <Header initials={initials} />;
};

thanks in advance

CodePudding user response:

return initials?.length && <Header initials={initials} />;

This is the problematic line. Since the return type should be a React element, you might want to return something digestable if your initials are not initialised. Although not the prettiest, returning empty fragment should work:

return initials?.length ? <Header initials={initials} /> : <></>

Alternatively, you can return null:

export const Home: FC = (): JSX.Element | null => {
  const [initials, setInitials] = useState<InitialProps[] | null>(null);
  useEffect(() => setInitials(initialInitialPropsSchema), []);
  return initials?.length ? <Header initials={initials} /> : null;
};

Or some loading state:

export const Home: FC = (): JSX.Element => {
  const [initials, setInitials] = useState<InitialProps[] | null>(null);
  useEffect(() => setInitials(initialInitialPropsSchema), []);
  return initials?.length ? <Header initials={initials} /> : <span>loading</span>;
};
  • Related