DEV Community

Vishang
Vishang

Posted on

4

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 (
      <ul>
        {this.props.list.map(function (friend) {
          return <li>{friend}</li>
        })}
      </ul>
    )
  }
}

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay