Before the release of React 15.5.0 version propTypes is available in the react package but in later versions of React have to add a dependency in your project. You can add the dependency in your project by using the command given below:
npm install prop-types --save
import PropTypes from 'prop-types';
Once we have imported propTypes we are ready to work with them. Just like defaultProps, propTypes are also objects where keys are the prop names and values are their types. Below syntax shows how to use propTypes:
import PropTypes from 'prop-types';
import React from 'react';
import ReactDOM from 'react-dom';
// Component
class ComponentExample extends React.Component{
render(){
return(
<div>
{/* printing all props */}
<h1>
{this.props.arrayProp}
<br />
{this.props.stringProp}
<br />
{this.props.numberProp}
<br />
{this.props.boolProp}
<br />
</h1>
</div>
);
}
}
// Validating prop types
ComponentExample.propTypes = {
arrayProp: PropTypes.array,
stringProp: PropTypes.string,
numberProp: PropTypes.number,
boolProp: PropTypes.bool,
}
// Creating default props
ComponentExample.defaultProps = {
arrayProp: ['Ram', 'Shyam', 'Raghav'],
stringProp: "GeeksforGeeks",
numberProp: "10",
boolProp: true,
}
ReactDOM.render(
<ComponentExample />,
document.getElementById("root")
);
References:
https://www.geeksforgeeks.org/reactjs-proptypes/
No comments:
Post a Comment