The real step-by-step guide to using Moment with React

April 30, 2021 — GitHub: Laura-TM

Laura M
3 min readApr 30, 2021

Moment.js is a free, open-source JavaScript library that allows you to use date and time features on your website. Of course, JavaScript already has many time and date functionalities that can make your life easier when trying to get a date or time stamp, but Moment.js outperforms on mathematical operations involving date and time, so there is your main reason to use it.

Photo by Moritz Kindler on Unsplash

Let’s now dig into installing and employing Moment.js!

STEP 1: Check the environment

First, ensure your server is not running (CTRL + C to kill it) and make sure you are running the following commands from the root of your project (the same directory as package.json):

For us newbies, it seems like this is the net’s best kept secret, but this will save you a lot of headaches down the line.

STEP 2: Install Moment.js

This is a very easy step! On your terminal, type: npm install — save moment react-moment. Below, an example of what it would look like:

Note, there are two hyphens before the word save

STEP 2.1: Installing time zone functionality

If you need to include time-zones, then you would need an extra step right at this point: npm install — save moment-timezone. Take a look below at what it would look like on the terminal:

STEP 2.2: Confirm Moment.js has been correctly installed

To check you have successfully installed Moment.js, check the node-modules folder on the left panel (below a screenshot from VS Code):

Open the dropdown list and look for the moment folder:

If you can find it, then you are good to go; otherwise, go back to the top and review the first steps again.

STEP 3: Import it into your project

Importing Moment.js is the same process as importing React, just type: import Moment from ‘react-moment’;

STEP 4: Using Moment.js on your components

You can now use any of the Moment.js functionalities on your project:

The above should output the date!!

Moment.js can be used to show calendar date and time, relative time, adding and subtracting dates and time… whatever your needs, check first whether you do require Moment.js or can use an alternative.

Happy coding to you all and don’t forget to be considerate with each other!

--

--

Laura M
Laura M

Written by Laura M

0 Followers

Junior developer

No responses yet