Home > Software design >  React Typescript Date Time Component (TypeError: Date is not a constructor)
React Typescript Date Time Component (TypeError: Date is not a constructor)

Time:07-25

I'm trying to create a React component using typescript. But showing some TypeError. I'm using Nextjs and Typescript. Actually, I wanted to show the Time and Date both. But when I use new Date() Function Then Shows an error massage that calls

const Date: () => JSX.Element
'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.

Here is my code

import React, { FC, ReactNode, useEffect, useState } from 'react'
import banner from "../assets/banner.png"
import Image from 'next/image'

const Date = (): JSX.Element => {
    const dateTime = new Date();
    const [clock, setClock] = useState<string>(dateTime.toLocaleDateString());
    

    useEffect(() => {
        const clock = setInterval(
            (): void => setClock(dateTime.toLocaleTimeString()),
            1000
        );

        return () => {
            clearInterval(clock);
        };
    }, []);

    return (
        <div className='w-full relative mb-3'>
            <Image
                className='rounded-xl w-full mx-auto'
                src={banner}
                alt="banner"
                width={700}
                height={240}
            />
            <div className='absolute rounded-xl w-full flex items-center h-full p-4 top-0 left-0'>
                <div className='ml-0 sm:ml-3'>
                    <h1 className='text-3xl md:text-4xl lg:text-6xl text-white font-bold'>
                        {new Date().toLocaleDateString(undefined, {
                            weekday: "long",
                            year: "numeric",
                            month: "long",
                            day: "numeric",
                        })}
                    </h1>
                    <p className='sm:text-xl mt-3 text-white font-bold'>{clock}</p>
                </div>
            </div>
        </div>
    )
}

export default Date

CodePudding user response:

Your component is named Date. So when you try const dateTime = new Date();, JS tries to invoke the constructor for your component, due to which you get the error, because it shadows the Date class from JS. Rename your component to something else, so that you can use the Date class from JS.

CodePudding user response:

This error occur because you are redefine Date constructor of javascript and when you call const dateTime = new Date() the compiler will think that you are using "Date function" you define above. Try again with a new function name:

const myDate: () => JSX.Element

  • Related