Skip to content

Latest commit

 

History

History
91 lines (71 loc) · 3.02 KB

07-react-validate-custom-react-component-props-with-proptypes-9e1b5b13.md

File metadata and controls

91 lines (71 loc) · 3.02 KB

07. Validate Custom React Component Props with PropTypes

Notes

  • When you create reusable React components, you want to make sure that people use them correctly. The best way to do this is to use TypeScript in your codebase to give you compile-time checking of your code.
  • If you’re not using TypeScript, you can still use PropTypes to get runtime validation.
  • Using PropTypes:
<body>
  <div id="root"></div>
  <script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
  <script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/[email protected]/babel.js"></script>
  <script type="text/babel">

    function SayHello({ firstName, lastName }) {
       return (
         <div>
           Hello {firstName} {lastName}!
         </div>
       );
     }

     const PropTypes = {
       string(props, propName, componentName) {
         if (typeof props[propName] !== 'string') {
           return new Error(
             `Hey, the component ${componentName} needs the prop ${propName} to be a string`
           );
         }
       }
     };

     SayHello.propTypes = {
         firstName: PropTypes.string.isRequired
         lastName: PropTypes.string
     }

     const element = <SayHello firstName={false}>

     ReactDOM.render(element, document.getElementById('root'));
  </script>
</body>
  • Using prop-types from unpkg:
<body>
  <div id="root"></div>
  <script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
  <script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>
  <script src="https://unpkg.com/@babel/[email protected]/babel.js"></script>
  <script src="https://unpkg.com/[email protected]/prop-types.js"></script>
  <script type="text/babel">
    const rootElement = document.getElementById('root');

    function SayHello({ firstName, lastName }) {
      return (
        <div>
          Hello {firstName} {lastName}!
        </div>
      );
    }

    // prop-types creates a global variable called propTypes
    // passing .isRequired
    SayHello.propTypes = {
      firstName: PropTypes.string.isRequired,
      lastName: PropTypes.string.isRequired
    };

    const element = <SayHello firstName={false} />;

    ReactDOM.render(element, rootElement);
  </script>
</body>

Additional resource