Moment.js with ReactJS (ES6)
I am new to Moment.js and using ReactJS (ES6) for my project. How can I use moment.js to format a date?
I want to format post.date
in the below mentioned loop.
render() {
return (
<div>
{
this.props.data.map((post,key) =>
<div key={key} className="post-detail">
<h1>{post.title}</h1>
<p>{post.date}</p>
<p dangerouslySetInnerHTML={{__html: post.content}}></p>
<hr />
</div>
)}
</div>
);
}
Since you are using webpack you should be able to just import
or require
moment and then use it:
import moment from 'moment'
...
render() {
return (
<div>
{
this.props.data.map((post,key) =>
<div key={key} className="post-detail">
<h1>{post.title}</h1>
<p>{moment(post.date).format()}</p>
<p dangerouslySetInnerHTML={{__html: post.content}}></p>
<hr />
</div>
)}
</div>
);
}
...
I know, question is a bit old, but since am here looks like people are still looking for solutions.
I'll suggest you to use react-moment
link,
react-moment
comes with handy JSX
tags which reduce a lot of work. Like in your case :-
import React from 'react';
import Moment from 'react-moment';
exports default class MyComponent extends React.Component {
render() {
<Moment format="YYYY/MM/DD">{this.props.dateToFormat}</Moment>
}
}
I have Used it as follow and it is working perfectly.
import React from 'react';
import * as moment from 'moment'
exports default class MyComponent extends React.Component {
render() {
<div>
{moment(dateToBeFormate).format('DD/MM/YYYY')}
</div>
}
}