Reputation: 27105
I cannot print simple JavaScript dates inside of React.
import React, { Component } from 'react';
import './ActivityWarningText.css';
class ActivityWarningText extends Component {
render() {
const str = new Date();
return(
<div>
<h1>All activity is recorded. {str}</h1>
</div>
)
}
}
export default ActivityWarningText;
I get this error:
Objects are not valid as a React child (found: Wed Apr 25 2018 18:09:03 GMT+0400 (Arabian Standard Time)). If you meant to render a collection of children, use an array instead.
in h1 (at index.js:17)
in div (at index.js:16)
in ActivityWarningText (at index.js:34)
in component (created by Route)
in Route (at index.js:34)
in div (at index.js:33)
in div (at index.js:30)
in Router (created by BrowserRouter)
in BrowserRouter (at index.js:29)
in App (at withAuthentication.js:36)
in WithAuthentication (at index.js:14)
This works however, str.getFullYear()
Upvotes: 3
Views: 5475
Reputation: 11
Objects can't be injected as children in react components. You can use the date.toISOString() function that would convert the date object into a thing that can be rendered as children to a react component.
Upvotes: 1
Reputation: 17269
new Date();
gives you an Object. You can't render Objects as children in React. You can get a stringified version of the date with toString()
.
Upvotes: 2
Reputation: 152294
Date
object has to be casted to string. You can try with
{str.toString()}
or
{`${str}`}
Upvotes: 6