Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>     ); } 
like image 680
Jahanzaib Aslam Avatar asked Jun 23 '16 13:06

Jahanzaib Aslam


People also ask

Can I use MomentJS in React?

The moment-timezone package is required to use the timezone related functions. Then import the package into your project. import React from 'react'; import Moment from 'react-moment'; import 'moment-timezone'; export default class App extends React. Component { ... }

What is Moment () in react JS?

For this, we'll be using a library called moment js. A lightweight JavaScript date library for parsing, validating, manipulating, and formatting dates.

Is moment deprecated?

Moment construction falls back to js Date. This is discouraged and will be removed in an upcoming major release. This deprecation warning is thrown when no known format is found for a date passed into the string constructor.

Is MomentJS still used?

Conclusion. MomentJS isn't completely gone yet. But on their website they suggest you look beyond Moment unless you fall into specific usecases. Luxon seems to be the biggest replacement for Moment that is futureproof for now.


1 Answers

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>     ); } ... 
like image 135
Davin Tryon Avatar answered Sep 18 '22 12:09

Davin Tryon