Requiring specific types

Sometimes, you need a property validator that checks for a type defined by your application. For example, let's say you have the following user class:

import cuid from 'cuid';

// Simple class the exposes an API that the
// React component expects.
export default class MyUser {
constructor(first, last) {
this.id = cuid();
this.first = first;
this.last = last;
}

get name() {
return `${this.first} ${this.last}`;
}
}

 

Now, suppose that you have a component that wants to use an instance of this class as a property value. You would need a validator that checks that the property value is an instance of MyUser. Let's implement a component that does just that:

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

import MyUser from './MyUser';

const MyComponent = ({ myDate, myCount, myUsers }) => (
<section>
{/* Requires a specific "Date" method. */}
<p>{myDate.toLocaleString()}</p>

{/* Number or string works here. */}
<p>{myCount}</p>
<ul>
{/* "myUsers" is expected to be an array of
"MyUser" instances. So we know that it's
safe to use the "id" and "name" property. */}
{myUsers.map(i => <li key={i.id}>{i.name}</li>)}
</ul>
</section>
);

// The properties spec is looking for an instance of
// "Date", a choice between a string or a number, and
// an array filled with specific types.
MyComponent.propTypes = {
myDate: PropTypes.instanceOf(Date),
myCount: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
myUsers: PropTypes.arrayOf(PropTypes.instanceOf(MyUser))
};

export default MyComponent;

This component has three properties that require specific types, each going beyond the basic type validators that you've seen so far in this chapter. Let's walk through these now:

  • myDate requires an instance of Date. It uses the instanceOf() function to build a validator function that ensures the value is a Date instance.
  • myCount requires that the value either be a number or a string. This validator function is created by combining oneOfType, PropTypes.number(), and PropTypes.string().
  • myUsers requires an array of MyUser instances. This validator is built by combining arrayOf() and instanceOf().

This example illustrates the number of scenarios that you can handle by combining the property validators provided by React. Here's what the rendered output looks like:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.224.197