How to use Reactjs with Moment.js (ES7)

They say nothing is certain but death, taxes and formatting dates in a web application. No matter what kind of projects you are developing on, the chance of formatting times and dates is bound to come up.

Date formatting libraries are one of the most frequently reached for utilities by web developers. With this in mind, how exactly can you use React.js with Moment.js?

Thankfully, this is made relatively simple by availing of a package called react-moment.  It allows the Moment library to be used like any other React component.

This is my personal preference as customizing my dates via props stays consistent with how I typically interact with elements of my application.

Install moment’s react library:

npm i react-moment

After the installation, import Moment and make use of the multiple ways you can interact with the library’s formatting capabilities via props:

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            const dateToFormat = '1976-04-19T12:59-0500';
            <Moment date={dateToFormat} />
        );
    }
}

Alternatively, we can also just import moment’s native package. Install moment’s standard package:

npm i -s moment

Import into your component:

import moment from 'moment'
...
render() {
    return (
        <div>
          <p>{moment('1976-04-19T12:59-0500').format()}</p>
        </div>
    );
}

We can call various methods from our moment import in order to access formatting utilities.

Here is a basic list from the moment docs:

moment().format('MMMM Do YYYY, h:mm:ss a'); // April 12th 2020, 12:02:02 pm
moment().format('dddd');                    // Sunday
moment().format("MMM Do YY");               // Apr 12th 20
moment().format('YYYY [escaped] YYYY');     // 2020 escaped 2020
moment().format();                          // 2020-04-12T12:02:02+01:00

And there we have it, there a such a wide range of date formatting utilities that momentjs provides for us. I’d suggest siphoning through the docs in order to find what works for you.

Proudly published with Gatsby