David Neto David Neto - 2 months ago 9
React JSX Question

Meteor and ReactJS - Date retrieved from MongoDB to String?

I'm following Meteor tutorial with ReactJS variant and making some experiments in the meanwhile. I'm new to Meteor, React and Mongo. My background is PHP, SQL and JS.

Currently I have a collection(table) 'tasks' which stores documents(rows) containing a 'text' field of type string and a 'createdAt' field of type Date.

To allow the displaying of a 'task', the following code is used:

// Task component - represents a single todo item
export default class Task extends Component {

render() {

return (
<li>
<span className="text">{this.props.task.text}</span>
</li>
);
}
}


Now, I want to display the 'createdAt' property of the task. Knowing that it comes from a javascript Date type I try the following:

return (
<li>
<span className="text">{this.props.task.text}</span><br/><br/>
<span className="createdAt">{this.props.task.createdAt}</span>
</li>
);


and

return (
<li>
<span className="text">{this.props.task.text}</span><br/><br/>
<span className="createdAt">{this.props.task.createdAt.toString()}</span>
</li>
);


When doing this the tasks no longer display and I get the following error message when inspecting the app:


Invariant Violation: Objects are not valid as a React child (found:
Fri Oct 07 2016 22:11:07 GMT+0200 (Romance Daylight Time)). 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
Task
.


I'm still somehow confused about React. What's the meaning of this error message referring to React child? And how can I fix it?

Answer

momentjs is a very good library to display and manipulate date and time. From your createdAt you can use

<span className="createdAt">
  {moment(this.props.task.createdAt).format(/*valid format, e.g. DD/MM/YYYY*/)
</span