PropTypes
suggest changeThe prop-types package allows you to add runtime type checking to your component that ensures the types of the props passed to the component are correct. For instance, if you don’t pass a name or isYummy prop to the component below it will throw an error in development mode. In production mode the prop type checks are not done. Defining propTypes can make your component more readable and maintainable.
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { AppRegistry, Text, View } from 'react-native';
import styles from './styles.js';
class Recipe extends Component {
static propTypes = {
name: PropTypes.string.isRequired,
isYummy: PropTypes.bool.isRequired
}
render() {
return (
<View style={styles.container}>
<Text>{this.props.name}</Text>
{this.props.isYummy ? <Text>THIS RECIPE IS YUMMY</Text> : null}
</View>
)
}
}
AppRegistry.registerComponent('Recipe', () => Recipe);
// Using the component
<Recipe name="Pancakes" isYummy={true} />
Multiple PropTypes
You can also allow more than one type for a single prop. For example, if name may be either a string or an object:
static propTypes = {
name: PropTypes.oneOfType([
PropTypes.string,
PropTypes.object
])
}
Children Props
There is also a special prop called children, which is not passed like this:
<Recipe children={something}/>
Instead, nest the content:
<Recipe>
<Text>Hello React Native</Text>
</Recipe>
Then, in Recipe's render:
return (
<View style={styles.container}>
{this.props.children}
{this.props.isYummy ? <Text>THIS RECIPE IS YUMMY</Text> : null}
</View>
)
You will have a <Text> component in your Recipe saying Hello React Native.
The prop type of children is:
children: PropTypes.node