I have a component like this
var Post = React.createClass({
render: function () {
return (
<li key={ this.props.message.uid }>
<div className="avatar">
<img src={ this.props.message.user.avatar } className="img-circle"/>
</div>
<div className="messages">
<p>{ this.props.message.content }</p>
<span className="date">{ "@"+this.props.message.user.login + " • " }</span>
<span className="date timeago" title={ this.props.message.createdAt }>
{ this.props.message.createdAt }
</span>
</div>
</li>
)
}
});
turns out that the createdAt
is a string like 1451589259845
and I want to format the date. How can I do that on ReactJS? I tried put new Date()
inside the brackets but got an error.
Now, let's see the below code example where we used the moment library for formatting dates in react. Here, we simply import the moment library and then use it within a formatDate variable. Here, in our case, the date will give output as day and then month and finally the year.
What is JSX? JSX stands for JavaScript XML. JSX allows us to write HTML in React. JSX makes it easier to write and add HTML in React.
Just do it in JS the usual way, before you start your return, and just template that in:
render: function() {
var cts = this.props.message.createdAt,
cdate = (new Date(cts)).toString();
return (
...
<span ...>{ cdate }</span>
...
);
}
And there are quite a few ways you can do the string formatting, Date has a number of them built in (like toLocaleString
or toUTCString
), or you can use a dedicated formatter like moment.js
You could just run the regular JavaScript New Date(). However, I would strongly recommend using momentjs, as it seems to be more in line with what you are trying to do.
On the command line do:
npm install moment --save
Then in your code either var moment = require("moment");
or
import moment from "moment";
depending on whether you are using ES6 or not.
After that, I would run code like so.
var timeAgo = moment(this.props.message.createdAt).fromNow()
<span className="date timeago" title={ timeAgo }>
{ timeAgo }</span>
Also, it may seem like a huge pain to install a package to do this, but moment is really nice and I would highly recommend it. The reason I recommended it is that it humanizes times. Like for instance, the fromNow() formatting makes it say 30 seconds ago, 4 days ago, or 3 months ago. It makes it sound like a person wrote it and it doesn't display tons of unnecessary info unless specified. I mean, most people don't want to know how many minutes and seconds ago it was if it was several hours ago. So, I recommended this library for those reasons. Feel free to use vanilla JS though if you prefer, I just find that moment is very nice for presentational purposes and let's me avoid having to write tons of math functions to display months, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With