React Short Notes 1: Typechecking React with PropTypes

You may also not want to skip type checking, as it helps to remove a great number of bugs

DevHoot

Summary

At most of the places, you’ll find people talking about using typechecking extensions such as Flow and, Typescript for React projects. These tools provide a lot of features and may be difficult to grasp when you are just starting out on your adventurous React journey. You may also not want to skip type checking, as it helps to remove a great number of bugs. As it happens, React has a core package called prop-types which provides some minimal type checking that would suffice many simple React projects. We will build a bookselling app.

Using prop-types

First, install prop-types:

yarn add prop-types 

prop-types is used on components you define. Let’s type-safe the name of our Book. To typecheck the props for a component, you can assign the propTypes property

import PropTypes from 'prop-types';

class Book extends React.Component { 
    render() { 
        return ( 
            <div>
             <h4>Title: {this.props.name}</h4> 
            </div> 
            );
        }
    } 
    
    Book.propTypes = { 
        name: PropTypes.string 
        } 
    
    ReactDOM.render(
        <Book name="Elegant Javascript" />,
         document.getElementById('root')); 

In the above example, we are using the Proptypes.string validator. PropTypes gives us a range of other validators as well. If a value with an incorrect type is passed in props, a warning is displayed in the console.

PropTypes Validators

  • For checking JS types.
Book.propTypes = {
     name: PropTypes.string, 
     sellers: PropTypes.array, 
     inStock: PropTypes.bool, 
     addToCart: PropTypes.func, 
     price: PropTypes.number, 
     publishInfo: PropTypes.object, 
    } 
  • Validating required props.

You may always want a certain prop to always be passed to a component. For this, you can use the isRequired property.

name: PropTypes.string.isRequired 
  • Accepting a prop of any type.
isdn: PropTypes.any 
  • Limited to specific values.
saleRegion: oneOf(['Argentina', 'India', 'Brazil']) 

There are more validators available. For the full list see PropTypes

Specifying Defaults for Props

For this, we use the defaultProps property.

Book.defaultProps = { price: 12 }; 

In the above example, if you don’t pass the price of a book in props, React will render 12 as the price.

Note: The default values should match the type defined for the props

Next Steps

  1. Start a new react project with prop-types.
  2. Integrate prop-types in an existing project.
  3. Explore other extensions of type checking like Flow, Typescript if prop-types doesn’t suffice your growing project.

Subscribe below or here to receive new content whenever I publish. 👇

No new content, No new e-mail. Promise !!!