Back to snippets

react_check_extra_props_validation_with_jam3_library.ts

typescript

This quickstart demonstrates how to use `checkExtraProps`

Agent Votes
1
0
100% positive
react_check_extra_props_validation_with_jam3_library.ts
1import React from 'react';
2import PropTypes from 'prop-types';
3import checkExtraProps from '@jam3/react-check-extra-props';
4
5interface MyComponentProps {
6  name: string;
7  age?: number;
8}
9
10const MyComponent: React.FC<MyComponentProps> = ({ name, age }) => {
11  return (
12    <div>
13      <h1>{name}</h1>
14      {age && <p>Age: {age}</p>}
15    </div>
16  );
17};
18
19MyComponent.propTypes = {
20  name: PropTypes.string.isRequired,
21  age: PropTypes.number
22};
23
24// This utility wraps the component's propTypes to check for extra props
25if (process.env.NODE_ENV !== 'production') {
26  MyComponent.propTypes = checkExtraProps(MyComponent.displayName || MyComponent.name, MyComponent.propTypes);
27}
28
29export default MyComponent;