When creating components, remember that they can be composed into bigger components and reused (in the same project, in other projects, by other developers). Therefore, it is a good practice to make explicit in your components which props can be used, which ones are required, and which types of values they accept.

import React, { Component, PropTypes } from 'react';
import { render } from 'react-dom';
class Greeter extends Component {
	render() {
		return (
			<h1>{this.props.salutation}</h1>
		)
	}
}
Greeter.propTypes = {
	salutation: PropTypes.string.isRequired
}

/*Default Prop Values*/
Greeter.defaultProps = {
	salutation: "Hello World"
}

render(<Greeter salutation="Hello World" />, document.getElementById('root'));

Javascript Primitives PropTypes

PropTypes.array: Prop must be an array.
PropTypes.bool: Prop must be a Boolean value (true/false).
PropTypes.func: Prop must be a function.
PropTypes.number: Prop must be a number (or a value that can be parsed into a number).
PropTypes.object: Prop must be an object.
PropTypes.string: Prop must be a string.

Combined Primitives PropTypes

PropTypes.oneOfType

An object that could be one of many types, such as

PropTypes.oneOfType([
	PropTypes.string,
	PropTypes.number,
	PropTypes.instanceOf(Message)
])

PropTypes.arrayOf

Prop must be an array of a certain type, such as

PropTypes.arrayOf(PropTypes.number)

PropTypes.objectOf

Prop must be an object with property values of a certain type, such as

PropTypes.objectOf(PropTypes.number)

PropTypes.shape

Prop must be an object taking on a particular shape. It needs the same set of properties, such as

PropTypes.shape({
	color: PropTypes.string,
	fontSize: PropTypes.number
})

Special PropTypes

PropTypes.node: Prop can be of any value that can be rendered: numbers, strings, elements, or an array.
PropTypes.element: Prop must be a React element.
PropTypes.instanceOf: Prop must be instance of a given class (this uses JS’s instanceof operator.), such as PropTypes.instanceOf(Message).
PropTypes.oneOf: Ensure that your prop is limited to specific values by treating it as an enum, like PropTypes.oneOf([‘News’, ‘Photos’]).

Custom PropType Validators

let titlePropType = (props, propName, componentName) => {
	if (props[propName]) {
		let value = props[propName];
		if (typeof value !== 'string' || value.length > 80) {
			return new Error(
			`${propName} in ${componentName} is longer than 80 characters`);
		}
	}
}

YourComponent.propTypes = {
	id: PropTypes.number,
	title: titlePropType,
	description: PropTypes.string,
	color: PropTypes.string,
	tasks: PropTypes.arrayOf(PropTypes.object)
};

 

ReactJS: Prop Validation

Category: Uncategorized
0
5887 views

Join the discussion

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