I need to create new empty div onClick every time not once, is it right way to do this in react, I just doubt if it is correct to do this in react
import "./styles.css";
export default function App() {
const parentRef = useRef();
const createNewDiv = () => {
parentRef.current.appendChild(document.createElement("div"));
};
return (
<div className="App">
<div onClick={createNewDiv} ref={parentRef}>
clickHere
</div>
</div>
);
}
Try to use react createElement method instead of using appendChild directly. Add new element in array and then display this array in the JSX.
import React, { useRef, useState } from "react"; import "./style.css"; export default function App() { const parentRef = useRef(); const [elements, setelements] = useState([]); const createNewDiv = () => { // parentRef.current.appendChild(document.createElement("div")); const newElement = React.createElement('div', {key: 'ele'+ new Date().getTime()}, `Hello`,); setelements(elements => [...elements,newElement]); }; return ( <div> <h1>Hello StackBlitz:</h1> <p>Start editing to see some magic happen;)</p> <div onClick={createNewDiv} ref={parentRef}> clickHere </div> { elements } </div> ); }
Here is the stackblitz example .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.