I was learning React and tried to display current date. But I am getting this error. I created a Date object and stored it in a variable and then displayed it on the h2 tag. Here's My code:
import logo from './logo.svg';
import './App.css';
function App() {
const curr_tim= new Date();
console.log(curr_tim);
return (
<div className='container'>
<h1>
React Clock
</h1>
<h2>Current Date is:{curr_tim}</h2>
</div>
);
}
export default App;
and I am getting this as error.
Uncaught Error: Objects are not valid as a React child (found: [object Date]). If you meant to render a collection of children, use an array instead.
at throwOnInvalidObjectType (react-dom.development.js:14887:1)
at updateSlot (react-dom.development.js:15202:1)
at reconcileChildrenArray (react-dom.development.js:15349:1)
at reconcileChildFibers (react-dom.development.js:15821:1)
at reconcileChildren (react-dom.development.js:19174:1)
at updateHostComponent (react-dom.development.js:19924:1)
at beginWork (react-dom.development.js:21618:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
CodePudding user response:
Like the error suggested, curr_tim is an object and React can't render object on the UI. You can try to turn it to something like new Date().toDateString()
, or any kind of date you would like. As long as it's a primitive type it would be fine
CodePudding user response:
Replace your code with This,
import logo from './logo.svg';
import './App.css';
function App() {
const curr_tim= new Date().toDateString();
console.log(curr_tim);
return (
<div className='container'>
<h1>
React Clock
</h1>
<h2>Current Date is:{curr_tim}</h2>
</div>
);
}
export default App;
Or With This,
import logo from './logo.svg';
import './App.css';
function App() {
const curr_tim= new Date();
console.log(curr_tim);
return (
<div className='container'>
<h1>
React Clock
</h1>
<h2>Current Date is:{curr_tim.toDateString()}</h2>
</div>
);
}
export default App;