Table of contents
No headings in the article.
The main difference between using PropTypes in functional components and class-based components in React is the way you declare them.
In class-based components, PropTypes are declared as a static property on the class itself. Here's an example:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class MyComponent extends Component {
static propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired,
isStudent: PropTypes.bool
};
render() {
const { name, age, isStudent } = this.props;
return (
<div>
<h1>{name}</h1>
<p>Age: {age}</p>
{isStudent && <p>Student</p>}
</div>
);
}
}
export default MyComponent;
In functional components, you declare PropTypes as a property on the function itself. Here's an example:
import React from 'react';
import PropTypes from 'prop-types';
function MyComponent({ name, age, isStudent }) {
return (
<div>
<h1>{name}</h1>
<p>Age: {age}</p>
{isStudent && <p>Student</p>}
</div>
);
}
MyComponent.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired,
isStudent: PropTypes.bool
};
export default MyComponent;
As you can see, the PropTypes declaration is separate from the function declaration in functional components, while it is included as a static property in class-based components. Both approaches achieve the same goal of validating props passed to a component and providing helpful error messages in case of incorrect usage.
It's worth noting that React Hooks have their own version of PropTypes called prop-types-exact
. When using Hooks in functional components, you can declare propTypes in the same way as the second example above.