PropTypes in a stateless functional component

Without using a class, how can I use PropTypes in a functional stand-alone response component?

export const Header = (props) => ( <div>hi</div> ) 
+70
javascript reactjs react-proptypes react-props
source share
2 answers

White papers show how to do this with ES6 component classes, but the same goes for stateless functional components.

First, npm install / yarn add new package of prop types , if you haven’t already.

Then add your propTypes (and defaultProps, if necessary) after the stateless functional component has been defined before exporting it.

 import React from "react"; import PropTypes from "prop-types"; const Header = ({ name }) => <div>hi {name}</div>; Header.propTypes = { name: PropTypes.string }; // Same approach for defaultProps too Header.defaultProps = { name: "Alan" }; export default Header; 
+107
source share

Saving state is no different. You can add it as follows:

 import PropTypes from 'prop-types'; Header.propTypes = { title: PropTypes.string } 

Here is the link to prop-types npm.

+18
source share

All Articles