Its return type 'Element | undefined' is not a valid JSX element. Type 'undefined' is not assignable to type 'Element | null'
Asked Answered
T

2

6

Using a setInterval, I made the effect of changing the screen after 3 seconds to make it look like a mobile application. And when I applied this to the app.tsx, an error occurred.

Landing/index.tsx

import React, { useRef, useEffect, useState } from "react";
import * as S from "./style";

const Landing = () => {
   const [sec, setSec] = useState<number>(3);
   const time = useRef<number>(3);
   const timerId = useRef<any>(null);

   useEffect(() => {
      timerId.current = setInterval(() => {
         setSec(time.current % 60);
         time.current -= 1;
      }, 1000);

      return () => clearTimeout(timerId.current);
   }, []);

   useEffect(() => {
      if (time.current == 0) {
         clearInterval(timerId.current);
      }
   }, [sec]);

   if (time.current == 3) {
      return (
         <>
            <S.Positioner>
               <S.Wrapper>
                  <S.TextWrapper>
                     <S.Text>Ayo The</S.Text>
                     <S.Title>Pizza Here</S.Title>
                  </S.TextWrapper>
                  <S.Copyright>©</S.Copyright>
               </S.Wrapper>
            </S.Positioner>
         </>
      );
   }
};

export default Landing;

_app.tsx

import React from "react";
import {Global} from "@emotion/react";
import {GlobalStyles} from "../style/GlobalStyle";
import Landing from "../components/Landing";
import Main from "../components/Main";
import Head from "next/head";

const MyApp = () => {
   return (
     <>
        <Head>
           <title>A-Pizza</title>
           <link rel="shortcut icon" href="/favicon.ico"/>
        </Head>
        <Global styles={GlobalStyles}/>
        <Landing/>
        <Main/>
     </>
   )
}

export default MyApp

If erase this code, the error on the app disappears How can I fix it? if (time.current == 3)

_app.tsx error image

Taub answered 24/5, 2022 at 5:56 Comment(0)
P
14

You need to return null or return <></> in case time.current is not 3. JS functions return undefined if nothing is returned explicitly. Typescript is complaining because undefined is not a valid react element.

Poverty answered 24/5, 2022 at 6:0 Comment(0)
G
5

Return jsx element is mandatory if not then you should return null atleast.

if (time.current == 3) {
   return (
      <>
         <S.Positioner>
            <S.Wrapper>
               <S.TextWrapper>
                  <S.Text>Ayo The</S.Text>
                  <S.Title>Pizza Here</S.Title>
               </S.TextWrapper>
               <S.Copyright>©</S.Copyright>
            </S.Wrapper>
         </S.Positioner>
      </>
   );
} else {
   return null;
}
Gynaecocracy answered 24/5, 2022 at 6:2 Comment(1)
Thanks, adding return null; fixed the error. For me all the return html code was within different if expressions.Salema

© 2022 - 2024 — McMap. All rights reserved.