c-poulsen c-poulsen - 1 month ago 32
React JSX Question

Objects are not valid as React child

I have a function which calculates the date from a unix timestamp

_getTime(time) {
var dateTime = new Date(time*1000);

console.log(dateTime);
return dateTime

},


The function is used in this

render: function() {
return (
{this.state.daily.map(day => {
return (
<div key={day.time} className="key col-md-12">
<div className="col-md-3">{this._getTime(day.time)}</div>
</div>
);
);
},


This returns
Invariant Violation: Objects are not valid as a React child (found: Thu Oct 20 2016 00:00:00 GMT+0200 (CEST)). 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
App
.


I am aware of there questions with the same error message, but I can't seem to figure out a solution for my problem.

Answer

Plain javascript:

_getTime(time) {
    var dateTime = new Date(time*1000).toString();    
    console.log(dateTime);
    return dateTime    
 },

Using moment.js

_getTime(time) {
    var dateTime = moment(time*1000).format('YYYY-MM-DD HH:mm:ss');    
    console.log(dateTime);
    return dateTime    
 },