O'Reilly logo

React Native By Example by Richard Kho

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Prop validation in React

By declaring a propTypes object for a component, I can specify the expected props and their types for a given component. This is helpful for future maintainers of our code and provides helpful warnings when props are incorrectly entered or missing.

To take advantage of prop validation, first import the PropTypes module from React:

import { PropTypes } from 'react'; 

Then, in our component, we give it a static property of propTypes:

class Example extends Component {   static propTypes = {     foo: PropTypes.string.isRequired,     bar: PropTypes.func,     baz: PropTypes.number.isRequired   } } 

In the preceding example, foo and baz are the required props for the Example component. foo is expected to be a string, while baz is ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required