Live updating time not displaying

Issue

I’m trying to make a component that displays a live updating date & time, but for whatever reason I can’t get either to actually show up on screen.
Here is the code

Only error in the console:
Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it

Solution

.toLocaleDateString() is a method, you didn’t execute it. You use a method as the React Element, that’s why you get the error.

Not this:

<div>{date.toLocaleDateString}</div>

It should be:

import React, { useState, useEffect } from "react";

export default function DateTime() {
  const [date, setDate] = useState<Date>(new Date());
  useEffect(() => {
    const update = setInterval(() => {
      setDate(new Date());
    }, 1000);
    return function cleanUp() {
      clearInterval(update);
    };
  });

  return (
    <>
      <div>{date.toLocaleDateString()}</div>
      <div>{date.toLocaleTimeString()}</div>
      <div>Hello world</div>
    </>
  );
}

Codesandbox

Answered By – slideshowp2

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published