Without using class, how do I use PropTypes in functional stateless component of react?
export const Header = (props) => (
<div>hi</div>
)
Firstly, npm install / yarn add the prop-types package if you haven't already. Then, add your propTypes (and defaultProps too if required) after the stateless functional component has been defined, before you export it.
Using PropTypes in React PropTypes is React's internal mechanism for adding type checking to components. React components use a special property named propTypes to set up type checking. When props are passed to a React component, they are checked against the type definitions configured in the propTypes property.
PropTypes are simply a mechanism that ensures that the passed value is of the correct datatype. This makes sure that we don't receive an error at the very end of our app by the console which might not be easy to deal with.
A functional component is always a stateless component, but the class component can be stateless or stateful. There are many distinct names to stateful and stateless components.
The official docs show how to do this with ES6 component classes, but the same applies for stateless functional components.
Firstly, npm install
/ yarn add
the prop-types package if you haven't already.
Then, add your propTypes
(and defaultProps
too if required) after the stateless functional component has been defined, before you export 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;
It isn't different with the stateful, You can add it like:
import PropTypes from 'prop-types';
Header.propTypes = {
title: PropTypes.string
}
Here is a link to prop-types npm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With