reactjsplunker

Plunker . How to require a react module?


I am trying to require a react React module on plnkr in the script.jsx file using :

var AptList = require('./AptList');

Which is giving a "require is not defined" error.

I would like to know how to require modules on plnkr ?


Solution

  • You are not using any bundler, everything is in the browser, so you have to first include the script for that AptList component in your index.html:

    <script src="AptList.js"></script>
    <script src="script.jsx"></script>
    

    That will already include the definition for that component. You need not (and cannot) use require there.

    In AptList.js you need not have module.exports = AptList; because it will already have been imported using the script tag above. Also, you should remove the require inside script.jsx.

    Now, the other big issue is you are using JSX, which is not supported natively by the browser. For that, you will need Babel, so add the following the scripts in index.html:

    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.js"></script>
    

    Then, you have to add the following type to each script tag at the bottom, before the end of body:

    <script type="text/babel" src="..."></script>
    

    That will allow you to use ES6 syntax and JSX.

    Here is the link to the plunk with everything working.