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
CodePudding user response:
.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>
</>
);
}