I wrote a react function in CodePem to test React hooks, however it constantly keeps reporting errors: Uncaught ReferenceError: require is not defined.
My Code:
import {useState, useEffect,useRef } from 'react';
function Test() {
const [count, setCount] = useState(0);
const prevRef = useRef();
useEffect(() => {
// const ref = useRef();
console.log('ref----', prevRef.current);
prevRef.current = count;
})
return (
<div>
<div onClick={() => setCount(count+1)}>+1</div>
<div>{`count: ${count}`}</div>
<div>{`precount: ${prevRef.current}`}</div>
</div>
)
}
ReactDOM.render(<Test />, document.getElementById("app"));
You can add a package by adjusting the settings in your Pen.
Take a look at the following image for reference:
By doing so, it will automatically generate the necessary import statement:
import React, { useState, useEffect, useRef } from 'https://esm.sh/react@18.2.0';
import ReactDOM from 'https://esm.sh/react-dom@18.2.0';
To help you understand this process, I've created a sample code on CodePen. You can refer to this example to implement it yourself.
Here is the codepen link to the sample code: https://codepen.io/camel2243/pen/ExdBRar