prop types in functional component code example
Example 1: proptypes oneof
import PropTypes from 'prop-types';
MyComponent.propTypes = {
optionalArray: PropTypes.array,
optionalBool: PropTypes.bool,
optionalFunc: PropTypes.func,
optionalNumber: PropTypes.number,
optionalObject: PropTypes.object,
optionalString: PropTypes.string,
optionalSymbol: PropTypes.symbol,
optionalUnion: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.instanceOf(Message)
])
};
Example 2: use propTypes in react function
import React from 'react';
import { PropTypes } from 'prop-types';
const student = (props) => {
return (
<div>
<p>Student Name: {props.name}</p>
<p>Age: {props.age}</p>
</div>
);
};
student.propTypes = {
name: PropTypes.string,
age: PropTypes.number
};
export default student;
Example 3: react propthpes or
size: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
]),