Search code examples
reactjscodepen

Importing react libraries into Codepen (namely prop-types)


There is a nice simple react ES6 example on codepen.

https://codepen.io/anon/pen/ZxXQxp/

I would like to use this as a base for some investigations I want to make in react type checking, namely the 'defaultProps' feature.

'DefaultProperies' is a very simple type checking feature but unfortunately it lives in another library now. At the top of my component I have to import it like this :

import PropTypes from 'prop-types';

What steps would I need to make in codepen to import an external react library? It seems like there is no possible way to import the most basic of react libraries.


Solution

  • You need to include the prop-types library in the Pen. To do so:

    1. click the settings button at the top right of the pen:   
    2. select the "JavaScript" tab
    3. set the preprocessor to "Babel"
    4. add react, react-dom, and prop-types to External Resources
      1. react: https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.development.js
      2. react-dom: https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.development.js
      3. prop-types: https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.js

    This is what the settings window should look like:

              

    Then, in your javascript, you may access PropTypes:

    const DumbButton = ({ name, label, onClick }) => (
      <button name={name} onClick={onClick}>{label}</button>
    )
    
    DumbButton.propTypes = {
      label: PropTypes.string.isRequired,
      name: PropTypes.string.isRequired,
      onClick: PropTypes.func.isRequired,
    }
    

    See this CodePen for a working example.