Categories
React Answers

How to Add Prop Validation for Date Objects with React?

Spread the love

Sometimes, we want to add prop validation for date objects with React.

In this article, we’ll look at how to add prop validation for date objects with React.

Add Prop Validation for Date Objects with React

To add prop validation for date objects with React, we can use the prop-types library.

To install it, we run:

npm i prop-types

Then we can use it by writing:

import React from "react";
import PropTypes from "prop-types";

const DateDisplay = ({ date }) => <p>{date.toString()}</p>;

DateDisplay.propTypes = {
  date: PropTypes.instanceOf(Date)
};

export default function App() {
  return <DateDisplay date={new Date(2021, 1, 1)} />;
}

We create the DateDisplay component that takes the date prop.

And to validate it, we set the propTypes property of it to an object with the date property.

We set the allowed type of date to only be a Date instance by writing:

PropTypes.instanceOf(Date)

Now we set the date prop to anything other than a Date instance, we’ll get an error in the console.

Conclusion

To add prop validation for date objects with React, we can use the prop-types library.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *