29
loading...
This website collects cookies to deliver better user experience
propTypes
to set up type checking. This can be done for both functional and class-based components.import React from "react";
import PropTypes from "prop-types";
const Person = ({ name, age }) => {
return (
<article>
<h1>{name}</h1>
<p>{age}</p>
</article>
);
};
Person.propTypes = {
name: PropTypes.string,
age: PropTypes.number,
};
export default Person;
PropTypes.any
- prop can be anythingPropTypes.bool
- prop needs to be true
or false
PropTypes.number
- prop needs to be any number
PropTypes.string
- prop needs to be any string
PropTypes.func
- prop needs to be a functionPropTypes.array
- prop needs to be Array
PropTypes.object
- prop needs to be Object
PropTypes.symbol
- prop needs to be Symbol
Person.propTypes = {
hobby: PropTypes.any,
male: PropTypes.bool,
age: PropTypes.number,
name: PropTypes.string,
secretTalent: PropTypes.func,
friends: PropTypes.array,
wallet: PropTypes.object,
skill: PropTypes.symbol,
};
prop
is React element(ie. <MyComponent />
) or anything else(ie. strings, numbers, etc...)PropTypes.element
- React elementPropTypes.node
- Anything that can be rendered. Numbers, strings, elements, or an array
Blog.propTypes = {
blogTitle: PropTypes.element,
blogBody: PropTypes.node,
};
prop
is an instance of the given class. This can be useful to check if prop
is an instance of the component, but it only works with class-based components.PropTypes.arrayOf
- Array of defined elementsPropTypes.shape
- Object containing defined properties(may contain additional properties)PropTypes.exact
- Object containing only defined properties(can't contain any additional properties)
Person.propTypes = {
friends: PropTypes.arrayOf(PropTypes.string),
father: PropTypes.shape({
name: PropTypes.string,
age: PropTypes.number,
}),
dog: PropTypes.exact({
name: PropTypes.string,
age: PropTypes.number,
}),
};
props
are optional by default. To ensure that certain prop is always passed. We can mark it as required by using isRequired
validator.Person.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired,
friends: PropTypes.arrayOf(PropTypes.string),
};
prop
is a valid email address.Error
when validation fails.Person.propTypes = {
email: (props, propName, componentName) => {
// Regex to test if email is correct
if (!/^[^\s@]+@[^\s@]+$/.test(props[propName])) {
return new Error(
`Invalid prop "${propsName}" supplied to "${componentName}"`
);
}
},
};
props
. We can do this by assigning them to defaultProps
property. The following example will set englishSpeaker
to true
if we forget to set the prop.Person.propTypes = {
englishSpeaker: PropTypes.bool,
};
Person.defaultProps = {
englishSpeaker: true,
};