'How can update the DOM if the state changes?
I've created the box container dynamically according to the input changes.
- If I entered 1, it will create one box
- If I change the input lets say 2, its create 3 box but it should create 2
import React from 'react';
import './style.css';
export default function App() {
const [value, setValue] = React.useState();
const boxRef = React.useRef();
function createBox() {
const div = document.createElement('div');
div.classList.add('mystyle');
div.style.backgroundColor = 'white';
div.addEventListener('click', () => {
let boxColor = div.style.backgroundColor;
if (boxColor === 'white') {
div.style.backgroundColor = 'red';
} else {
div.style.backgroundColor = 'white';
}
});
return div;
}
React.useEffect(() => {
for (let i = 0; i < value; i++) {
const boxElement = createBox();
boxRef.current.appendChild(boxElement);
}
}, [value]);
function handleBoxCreate({ target: { value } }) {
setValue(value);
}
return (
<div>
<h1>BOX CREATE</h1>
<input type="number" name="boxInput" onChange={handleBoxCreate} />
<div ref={boxRef} />
</div>
);
}
/* style.css */
.mystyle {
width: 30px;
height: 30px;
border: 2px solid black;
display: inline-block;
padding: 2px;
margin-right: 5px;
}
Do I need to cleanup the dom. if so how to do it?. or is there any better way to implement the same.
Please help. ty:)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
