1
votes

Just learning the hook side of things with React. The class components makes sense, but Hooks are missing the render section.

If I'm adding React to a web page, (NOT THE CREATE REACT APP), how do I let my hook know where to run on the HTML page?

I'm trying to place code inside the following: <script src="react-hooks.js"></script>

Here's my hook code:

import React, { useState } from 'react';

function Example() {
    const [count, setCount] = useState(0);

    return (
        <div>
            <p>You clicked {count} times</p>
            <button onClick={() => setCount(count + 1)}>
                Click Me
            </button>
        </div>
    );
}

However, there's no place in a hook to say this anywhere. I've tried this:

const rootElement = document.getElementById("hook-section");
ReactDOM.render(<Example />, rootElement);

but I get the following error:

quote Uncaught SyntaxError: Cannot use import statement outside a module >quote

If I update the script call to include type="module"n I get the following:

quoteAccess to script at 'file:///C:/Users...react-hooks.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. index.html:44

quoteGET file:///C:/Users/.../react-hooks.js net::ERR_FAILED

Classes still work just fine, but not hooks. I am adding js files in a /src file, which when I run babel, it creates a another js version on the root.

I went off the React docs for this. https://reactjs.org/docs/add-react-to-a-website.html

Step 1: Run npm init -y (if it fails, here’s a fix)

Step 2: Run npm install babel-cli@6 babel-preset-react-app@3

npx babel --watch src --out-dir . --presets react-app/prod

1

1 Answers

2
votes

UPDATE

Ok, so the solution was setting the type=module in package.json, but now you have a new problem, a CORS error.

You are attempting the load the file from your local filesystem. Do you have a web server running on your local machine? If not, you need to set up a basic server locally to fix the CORS error. Alternatively, you could host the project through a hosting platform such as GitHub.


Verify that you have the latest version of Node installed. You can update your version of node with:

nvm install 12.16.1

nvm use 12.16.1

The --experimental-modules flag is no longer necessary. Simply do one of the following:

Add "type": "module" to the nearest parent package.json. With this, all .js and .mjs files are interpreted as ES modules.

package.json

{
    "type":"module"
}

OR

Explicitly name files with the .mjs extension. All other files, such as .js will be interpreted as CommonJS, which is the default if type is not defined in package.json.

mv react-hooks.js react-hooks.mjs