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
JavaScript
x
42
42
1
import React from 'react';
2
import './style.css';
3
4
export default function App() {
5
const [value, setValue] = React.useState();
6
const boxRef = React.useRef();
7
8
function createBox() {
9
const div = document.createElement('div');
10
div.classList.add('mystyle');
11
div.style.backgroundColor = 'white';
12
div.addEventListener('click', () => {
13
let boxColor = div.style.backgroundColor;
14
if (boxColor === 'white') {
15
div.style.backgroundColor = 'red';
16
} else {
17
div.style.backgroundColor = 'white';
18
}
19
});
20
return div;
21
}
22
23
React.useEffect(() => {
24
for (let i = 0; i < value; i++) {
25
const boxElement = createBox();
26
boxRef.current.appendChild(boxElement);
27
}
28
}, [value]);
29
30
function handleBoxCreate({ target: { value } }) {
31
setValue(value);
32
}
33
34
return (
35
<div>
36
<h1>BOX CREATE</h1>
37
<input type="number" name="boxInput" onChange={handleBoxCreate} />
38
<div ref={boxRef} />
39
</div>
40
);
41
}
42
JavaScript
1
10
10
1
/* style.css */
2
.mystyle {
3
width: 30px;
4
height: 30px;
5
border: 2px solid black;
6
display: inline-block;
7
padding: 2px;
8
margin-right: 5px;
9
}
10
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:)
Advertisement
Answer
You should avoid doing direct manipulations on the DOM. Instead create a “Box” react component and render it based on the amount of your value state.
JavaScript
1
41
41
1
import React from "react";
2
import "./styles.css";
3
4
const Box = () => {
5
const [color, setColor] = React.useState("white");
6
7
const onClick = () => {
8
if (color === "white") {
9
setColor("red");
10
} else {
11
setColor("white");
12
}
13
};
14
return (
15
<div
16
className="mystyle"
17
style={{ backgroundColor: color }}
18
onClick={onClick}
19
/>
20
);
21
};
22
23
export default function App() {
24
const [value, setValue] = React.useState(0);
25
26
function handleBoxCreate({ target: { value } }) {
27
setValue(Number(value));
28
}
29
30
return (
31
<div>
32
<h1>BOX CREATE</h1>
33
<input type="number" name="boxInput" onChange={handleBoxCreate} />
34
{[Array(value)].map((e, i) => (
35
<Box key={i} />
36
))}
37
</div>
38
);
39
}
40
41