Last active
August 22, 2019 16:46
-
-
Save joeynguyen/4e349b9f2dd7c6ea19d8b9c1833b72ed to your computer and use it in GitHub Desktop.
custom PropTypes validator for Moment object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import moment from 'moment'; // tested using v2.24.0 | |
// custom PropType validator per example at | |
// https://github.com/facebook/prop-types/blob/v15.7.2/README.md#usage | |
export function isMomentPropType(props, propName, componentName) { | |
if (!moment.isMoment(props[propName])) { | |
return new Error( | |
`Invalid prop ${propName} supplied to ` + | |
`${componentName} is not a Moment object. Validation failed.` | |
); | |
} | |
return null; | |
} | |
isMomentPropType.isRequired = () => null; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Jest test | |
import PropTypes from 'prop-types'; // tested using v15.7.2 | |
import moment from 'moment'; // tested using v2.24.0 | |
import { isMomentPropType } from './index'; | |
// Test using example from | |
// // https://github.com/facebook/prop-types/blob/v15.7.2/README.md#proptypescheckproptypes | |
test('isMomentPropType validates valid moment object', () => { | |
// define your prop validations | |
const myPropTypes = { | |
momentDate: isMomentPropType.isRequired, | |
}; | |
// pass props values | |
const props = { | |
momentDate: moment(), | |
}; | |
// validate | |
PropTypes.checkPropTypes(myPropTypes, props, 'momentDate', 'MyComponent'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment