I am following a code snippet from the book React Quickly
.
And I can not run the code after being compiled via babel.
My code is like:
class DateTimeNow extends React.Component{
render(){
let dateTimeNow = new Date();
return <span>Current date and time is {dateTimeNow}.</span>;
}
}
ReactDOM.render(
<DateTimeNow/>,
document.getElementById('content')
);
The error message reported by browser is:
Uncaught Invariant Violation: Objects are not valid as a React child (found: Mon Oct 17 2016 09:12:00 GMT+0800 (CST)). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of
DateTimeNow.
Could you please help to answer why it will cause error?
Thank you very much!
Do you want to request a _feature_ or report a _bug_?
What is the current behavior?
error message: Uncaught Invariant Violation: Objects are not valid as a React child (found: Mon Oct 17 2016 09:12:00 GMT+0800 (CST)). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of DateTimeNow
.
If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem via https://jsfiddle.net or similar (template: https://jsfiddle.net/reactjs/69z2wepo/).
What is the expected behavior?
span tag displays current time
Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?
React 15.3.2
The short answer is you need to call a toString()
method on your dateTimeNow variable, as it is a date _object_, and not a string. i.e. one of the 'Objects' the error message is referring to.
return <span>Current date and time is {dateTimeNow.toUTCString()}.</span>;
That said, the error message is initially confusing since it simply renders the date as a string. If for example you replace {dateTimeNow}
with an object such as { {a: 1} }
, the error message makes a little more sense:
Uncaught Error: Objects are not valid as a React child (found: object with keys {a}).
https://github.com/facebook/react/issues/7988#issuecomment-254148427 is correct.
Dates are objects in JS, but your render output may only contain React elements, strings, and numbers. Formatting a string with any toString()
-like method will work.
You can find a list of such methods on MDN.
Cheers!
why can't React do calling .toString()
for us automatically a l谩 string interpolation? Too much overhead?
Most helpful comment
The short answer is you need to call a
toString()
method on your dateTimeNow variable, as it is a date _object_, and not a string. i.e. one of the 'Objects' the error message is referring to.That said, the error message is initially confusing since it simply renders the date as a string. If for example you replace
{dateTimeNow}
with an object such as{ {a: 1} }
, the error message makes a little more sense: