PropTypes
Summary
Runtime type checking for React props and similar objects.
Overview
As your app grows, you can catch a lot of bugs with typechecking. For some applications, you can use JavaScript
extensions like Flow
or TypeScript
to typecheck your whole application.
But even if you don’t use those, the React.PropTypes library
offers some crucial typechecking abilities.
PropTypes
was originally exposed as part of the React core module, and is commonly used with React components to type check props.
React.PropTypes
has moved into a different package since React v15.5
. Please use the prop-types
library instead.
Installation
index.html
If you are using ES Modules you will need to import PropTypes
in your .js| .jsx
files:
Usage
Add the following code:
main.js
//same with function components// function Greeter(props) {// return <h1>Hello, {props.name}</h1>;// }class Greeter extends React.Component {render() {return <h1>Hello, {this.props.name}</h1>;}}Greeter.propTypes = {name: PropTypes.string.isRequired,};const element = <Greeter name="Joe" />;ReactDOM.createRoot(document.getElementById("root")).render(element);Change PropType to object.
main.js
...Greeter.propTypes = {name: PropTypes.object.isRequired};...You should receive the following warning in the browser
console
.Warning: Failed prop type: Invalid prop `name` of type `string` supplied to `Greeter`, expected `object`.in Greeter