Jahanzaib Aslam Jahanzaib Aslam -4 years ago 173
React JSX Question

Moment js with React js (ES6)

I am new to react js. I am using Reactjs(ES6) for my new project. How can I use moment.js to format date?

I want to format my

post.date
in 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>
);
}

Answer Source

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>
    );
}
...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download