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
In Create React App, where you would be using ES Modules you will need to
import PropTypes from "prop-types;"but you do not need to in this demonstration.
Usage
- Add the following code with the - propTypesdeclaration commented out and don't pass the required- nameprop as shown below:- main.jsfunction Greeter(props) {return <h1>Hello, {props.name}</h1>;}// Greeter.propTypes = {// name: PropTypes.string.isRequired,// };const element = <Greeter />;ReactDOM.createRoot(document.getElementById("root")).render(element);
- Notice it runs without an error. 
- Uncomment the - propTypesdeclaration.- main.jsfunction Greeter(props) {return <h1>Hello, {props.name}</h1>;}Greeter.propTypes = {name: PropTypes.string.isRequired,};const element = <Greeter name="Joe" />;ReactDOM.createRoot(document.getElementById("root")).render(element);
- Notice you receive a helpful warning message in the console. 
- Pass the - nameproperty the string- Srini.- main.jsfunction Greeter(props) {return <h1>Hello, {props.name}</h1>;}Greeter.propTypes = {name: PropTypes.string.isRequired,};const element = <Greeter name="Srini" />;ReactDOM.createRoot(document.getElementById("root")).render(element);
- Notice the code works and runs without any warning messages. 
- Pass the - nameproperty a number.- main.js...const element = <Greeter name={1} />;...
- Notice you receive a helpful warning message in the console.