Declaring Prop Types
ReactJS allows developers to use type checking to find bugs and resolve errors during development. For performance issues, type checking is only available during the development process. There are different ways to perform type checking in React. All of these ways are done using PropTypes
PropTypes allows you to validate data. You can specify if a piece of data should have a string, object, number or primitive data value. If your data is not validated it will throw a type error.
Method #1: Call Prop Types On Your Data
import PropTypes from 'prop-types';
class Greeting extends React.Component {
constructor(props) {
super(props);
this.sayHello = this.sayHello.bind(this);
}
sayHello(name) {
name = this.props.name;
return `Hello ${name}`
}
render() {
return (
<h1>{this.sayHello}</h1>
);
}
}
Greeting.propTypes = {
name: PropTypes.string,
sayHello: PropTypes.func
};
Method #2: Declare Default Props
Declaring Default Props lets you specify a value for that specific prop even if the parent component has not passed it a value
class Greeting extends React.Component {
render() {
return (
<h1>Hello, {this.props.name}</h1>
);
}
}
// Specifies the default values for props:
Greeting.defaultProps = {
name: 'Stranger'
};
// Renders "Hello, Stranger":
ReactDOM.render(
<Greeting />,
document.getElementById('example')
);
Method #3: Require A Single Child
With
PropTypes.element
you can specify that only a single child can be passed to a component as children.import PropTypes from 'prop-types'; class MyComponent extends React.Component { render() { // This must be exactly one element or it will warn. const children = this.props.children; return ( <div> {children} </div> ); } } MyComponent.propTypes = { children: PropTypes.element.isRequired };