0

I have created a simple HTML file, and added React into it through the CDN links.

    <html>
    <head>
        <title>React App</title>

        <script crossorigin="anonymous" src="https://unpkg.com/react@17/umd/react.development.js"></script>
        <script crossorigin="anonymous" src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
        <script crossorigin="anonymous" src="https://unpkg.com/babel-standalone@6/babel.min.js" ></script>

        <script type="text/babel" src="App.js"></script>
        <script type="text/babel" src="Button.js"></script>   <-- I don't want to include this in the HTML file, rather it should be included in App.js
    </head>
    <body>
    <div id="root"></div>

        <script type="text/babel">
            ReactDOM.render(<App />, document.getElementById('root'));
        </script>

    </body>
    </html>

I have created two React components:

App.js

const App = () => {
    return (
        <Button/>
        );
}

Button.js

const Button = () => {
    return (
        <input type="button" value="Click Me" />
    );
}

This works perfectly fine. However, I don't want to include <script type="text/babel" src="Button.js"></script> into the HTML file, rather I am trying to find a way to include Button.js component in the App.js and I should only add <script type="text/babel" src="App.js"></script> in the HTML file.

I tried various options like using import/export, require, but seems non of them are working. Appreciate any help around this.

  • Most modern browsers should be able to handle [`import`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules). Can you share how you were trying to do that please? – Matthew Herbst Feb 03 '22 at 09:29
  • Define the Button component in the same file, App.js before the App component. And then just remove Button.js – Shreshth Feb 03 '22 at 09:33
  • @MatthewHerbst this is how I tried with import in the App.Js file. "import Button from './Button';". And, in the Button.js, I am exporting it this way "export default Button;" – Sunny Dewangan Feb 03 '22 at 11:21
  • I get errors, "require is not defined", "exports is not defined", "react-dom.development.js:25088 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports." – Sunny Dewangan Feb 03 '22 at 11:24
  • @Shreshth I want to keep the components in separate files as I will have several components in the project, so it would be easier to manage them separately. – Sunny Dewangan Feb 03 '22 at 11:28
  • https://stackoverflow.com/questions/54018182/how-to-make-script-type-both-text-babel-and-module – Shreshth Feb 03 '22 at 13:47

0 Answers0