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