Why it is important to use React PropTypes

React PropTypes is a small package and since v15.5. of React it is separate package that is not required ti use React. But you should use and I will tell you why. The main purpose of the PropTypes is to make a validation of the props in React Apps and props is the main way to communicate between Parent and Child components. For example:
class ChildComponent extends React.Component{
  render() {
    return (
      <p>
        <i>{this.props.id}</i>: {this.props.message}
      </p>
    );
  }
};
class ParentComponent extends React.Component {
  render() {
      return <ChildComponent message="Hello World!" id={1}/>;
  }
};
In this code example ChildComponent would get the message via this.props.message, everything great so far! But As your app grows, you can catch a lot of bugs with typechecking. And that’s where the PropTypes is great. Here is another example of ChildComponent in which the type of data is checked:
import PropTypes from 'prop-types';

class ChildComponent extends React.Component {
    render() {
      return (
        <p>
          <i>{this.props.id}</i>: {this.props.message}
        </p>
        );
    }
}

ChildComponent.propTypes = {
  message: React.PropTypes.string.isRequired
  id: React.PropTypes.number.isRequired
};
ChildComponent does exactly the same as before, however, by reading the propTypes everyone will know that to pass in a property called message the type must be string. So what happens if you do not conform to the defined propTypes? Well if you provide a prop of the wrong type or don’t provide a required prop, React will log a warning to the console at runtime. Although propTypes are optional, you should always use them as it will help you in the future.

Leave a Reply

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