Basic type validation

Let's take a look at validators that handle the most primitive types of JavaScript values. You will use these validators frequently, as you'll want to know that a property is a string or that it's a function, for example. This example will also introduce you to the mechanisms involved with setting up validation on a component. Here's the component; it just renders some properties using basic markup:

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

const MyComponent = ({
myString,
myNumber,
myBool,
myFunc,
myArray,
myObject
}) => (
<section>
{/* Strings and numbers can be rendered
just about anywhere. */}
<p>{myString}</p>
<p>{myNumber}</p>

{/* Booleans are typically used as property values. */}
<p>
<input type="checkbox" defaultChecked={myBool} />
</p>

{/* Functions can return values, or be assigned as
event handler property values. */}
<p>{myFunc()}</p>

{/* Arrays are typically mapped to produce new JSX elements. */}
<ul>{myArray.map(i => <li key={i}>{i}</li>)}</ul>

{/* Objects typically use their properties in some way. */}
<p>{myObject.myProp}</p>
</section>
);

// The "propTypes" specification for this component.
MyComponent.propTypes = {
myString: PropTypes.string,
myNumber: PropTypes.number,
myBool: PropTypes.bool,
myFunc: PropTypes.func,
myArray: PropTypes.array,
myObject: PropTypes.object
};

export default MyComponent;

There are two key pieces to the property validation mechanism. First, you have the static propTypes property. This is a class-level property, not an instance property. When React finds propTypes, it uses this object as the property specification of the component. Second, you have the PropTypes object from the prop-types package, which has several built-in validator functions.

The PropTypes object used to be built into React. It was split from the React core and moved into the prop-types package so that it became an opt-in to use – a request by React developers that do not use property validation.

In this example, MyComponent has six properties, each with their own type. When you look at the propTypes specification, you can see what type of values this component will accept. Let's render this component with some property values:

import React from 'react';
import { render as renderJSX } from 'react-dom';

import MyComponent from './MyComponent';

// The properties that we'll pass to the component.
// Each property is a different type, and corresponds
// to the "propTypes" spec of the component.
const validProps = {
myString: 'My String',
myNumber: 100,
myBool: true,
myFunc: () => 'My Return Value',
myArray: ['One', 'Two', 'Three'],
myObject: { myProp: 'My Prop' }
};

// These properties don't correspond to the "<MyComponent>"
// spec, and will cause warnings to be logged.
const invalidProps = {
myString: 100,
myNumber: 'My String',
myBool: () => 'My Reaturn Value',
myFunc: true,
myArray: { myProp: 'My Prop' },
myObject: ['One', 'Two', 'Three']
};

// Renders "<MyComponent>" with the given "props".
function render(props) {
renderJSX(
<MyComponent {...props} />,
document.getElementById('root')
);
}

render(validProps);
render(invalidProps);

The first time <MyComponent> is rendered, it uses the validProps properties. These values all meet the component property specification, so no warnings are logged in the console. The second time around, the invalidProps properties are used, and this fails the property validation, because the wrong type is used in every property. The console output should look something like the following:

Invalid prop `myString` of type `number` supplied to `MyComponent`, expected `string` 
Invalid prop `myNumber` of type `string` supplied to `MyComponent`, expected `number` 
Invalid prop `myBool` of type `function` supplied to `MyComponent`, expected `boolean` 
Invalid prop `myFunc` of type `boolean` supplied to `MyComponent`, expected `function` 
Invalid prop `myArray` of type `object` supplied to `MyComponent`, expected `array` 
Invalid prop `myObject` of type `array` supplied to `MyComponent`, expected `object` 
TypeError: myFunc is not a function 

This last error is interesting. You can clearly see that the property validation is complaining about the invalid property types. This includes the invalid function that was passed to myFunc. So, despite the type checking that happens on the property, the component will still try to call the value as though it were a function.

Here's what the rendered output looks like:

Once again, the aim of property validation in React components is to help you discover bugs during development. When React is in production mode, property validation is turned off completely. This means that you don't have to concern yourself with writing expensive property validation code; it'll never run in production. However, the error will still occur, so fix it.
..................Content has been hidden....................

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