DEV Community


Posted on

React Prop-Types

PropTypes with React

If we create a component which accepts props as an array, what will happen when user by-mistake pass a string instead of an array. Yes, you're right. It will break. So at this point react Prop Types comes into play.

class Users extends React.Component {
  render() {
    return (
        { (friend) {
          return <li>{friend}</li>

Imagine if I pass string as a prop to a component

<Users list="Jason, Minky, Orio" />

Everything will break as string does not have a map functions with it. So to avoid this issue we can use Proptypes.

PropTypes allow you to declare the "type" (string, number, function, etc) of each prop being passed to a component. Then, if a prop passed in isn't of the declared type, you'll get a warning in the console.

Users.propTypes = {
list: PropTypes.array.isRequired

In order to use PropTypes, you'll need to install them. Note: They used to be included with React, but as of React 15.5 they were made they're own package which can be downloaded from npm as prop-types.

PropTypes are great for finding bugs in your components but what I like most about them is their ability to add documentation to a component. When I look at a well written component, I can look at the render method to figure out what it's going to look like and I can look at its propTypes to figure out what it needs to accept to render properly.

To check more in depth API click here

Oldest comments (0)