defaultprops react code example
Example 1: default props react
// ES6 class
class CatComponent extends React.Component {
constructor(props) {}
render() {
return {this.props.catName} Cat,
Eye Color: {this.props.eyeColor },
Age: {this.props.age}
}
}
CatComponent.defaultProps = {
catName: "Sandy",
eyeColor: "deepblue",
age: "120"
}
Example 2: proptypes oneof
import PropTypes from 'prop-types';
MyComponent.propTypes = {
// You can declare that a prop is a specific JS type. By default, these
// are all optional.
optionalArray: PropTypes.array,
optionalBool: PropTypes.bool,
optionalFunc: PropTypes.func,
optionalNumber: PropTypes.number,
optionalObject: PropTypes.object,
optionalString: PropTypes.string,
optionalSymbol: PropTypes.symbol,
// An object that could be one of many types
optionalUnion: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.instanceOf(Message)
])
};
Example 3: react proptypes
import PropTypes from 'prop-types';
class Greeting extends React.Component {
render() {
return (
Hello, {this.props.name}
);
}
}
Greeting.propTypes = {
name: PropTypes.string
};
Example 4: proptypes.arrayof/()
optionalArrayOf: PropTypes.arrayOf(PropTypes.number)
Example 5: defaultProps in react
defaultProps in react