Moment.js Prop Types for React

1.8.1 · active · verified Sun Apr 19

react-moment-proptypes provides custom React PropTypes for validating `moment` objects, `moment` duration objects, and strings that `moment` can parse into valid dates. It ensures that React components receive expected date/time formats, leveraging the `moment.js` library. The current stable version is 1.8.1. Releases appear to be driven by dependency updates and bug fixes rather than a strict schedule, with recent activity focusing on modernizing development dependencies and addressing compatibility issues. It is a utility layer bridging React's prop-type validation system with Moment.js's data structures, allowing developers to define robust type checks for time-related props without manual validation logic.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define and use `react-moment-proptypes` within a React component. It showcases `momentObj` for Moment objects, `momentString` for date strings, and `momentDurationObj` for Moment durations, including using `withPredicate` for custom validation.

import React from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import momentPropTypes from 'react-moment-proptypes';

class TestComponent extends React.Component {
  render() {
    return (
      <div>
        <p>Date Prop: {this.props.dateThing?.format('YYYY-MM-DD')}</p>
        <p>UTC Date Prop: {this.props.dateThingWithPredicate?.format('YYYY-MM-DD HH:mm [UTC]')}</p>
        <p>String Date Prop: {this.props.stringThing}</p>
        <p>Duration Prop: {this.props.durationThing?.humanize()}</p>
      </div>
    );
  }
}

TestComponent.propTypes = {
  dateThing: momentPropTypes.momentObj,
  dateThingWithPredicate: momentPropTypes.momentObj.withPredicate(
    function isUTC(momentObject) {
      return momentObject.isUTC();
    }
  ),
  stringThing: momentPropTypes.momentString,
  durationThing: momentPropTypes.momentDurationObj
};

// Example Usage
const App = () => (
  <TestComponent
    dateThing={moment()}
    dateThingWithPredicate={moment.utc()}
    stringThing={'12-12-2014'}
    durationThing={moment.duration(3, 'hours')}
  />
);

export default App;

view raw JSON →