Day 144 - TypeChecking With PropTypes

Last three post we learned about Styled-Components which is used to style application by writing CSS directly in JS and React. I liked it a lot and now thinking of again rewriting CSS of this blog completely with Styled-Components but later on that. Now we will be learning about PropTypes.

In React we build application by breaking the UI in small resuable components and we also need to pass data from one component to the other more commonly from parent to a child. We pass this data through Component Properties or in React know as props.

When passing data through props we have to make sure that the data we are passing and receiving must be the one we are expecting. Like if we are expecting a props to be of type String we must check if it is a prop of type String. To do this type checking we can use either TypeScript or if you are not working with TS then with a library called props-types.

PropTypes

PropTypes in a React App ensures that the right type of prop is passed to a child component and a child component is receiving the right type of props. As our application grows we can catch a lot of bugs before hand using type checking.

Prior to version 15 of React, PropTypes were builtin in React. But now we have to install a library for PropTypes. To install, run the following command.

$ npm i prop-types

Usage

To use PropTypes we first have to import them and then first we must have a Component on which we want to define PropTypes.

Consider this following example. We have a Post component with an Author component nested inside it. The Author component receives props from the Post component and we have to check that we have received the right type of props.

const Post = props => {
  const { content, author } = props;

  return (
    <div>
      <p>{content}</p>
      <br />
      <Author author={author} />
    </div>
  );
};

In the Author.js file we can define the PropTypes as following.

// Author.js
import PropTypes from "prop-types";

const Author = props => {
  return (
    <div>
      <h2>
        {props.firstName} {props.lastName}
      </h2>
      {props.active ? "Online" : "Offline"}
    </div>
  );
};

Author.propTypes = {
  firstName: PropTypes.string.isRequired,
  lastName: PropTypes.string,
  active: PropTypes.bool,
};

export default Author;

Below the Author component we are defining the PropsTypes for it and this will ensure that the props that we receive from the Post component are of right types. In the Author.propTypes object we define the name of the props we will be receiving and the type of those props with the PropTypes library. Note there is a isRequired in front of the firstName and it will ensure that the Post component must provide the firstName prop to the Author component.

All of the PropTypes of the props that we can pass to a component are list on the Official React Documentation Website. You can check them out -> Here <-.


zainscizainsci