I am learning react and built a simple program that generates array and changing it's color. I don't understand why when I generate new array the color of the previous one is kept. I thought that happened because the state has changed when I generated a new array react will re-render the component and the color will be set back to default. What am I missing?
Here is my code:
import React, { useState, useEffect } from 'react';
const Dummy2 = () => {
const [arr, setArr] = useState([]);
useEffect(() => {
generateArray();
}, []);
const generateArray = () => {
const temp = [];
for(let i = 1; i < 11; i++) {
temp.push(i * 2);
}
setArr(temp);
}
const changeColor = () => {
const arrayElements = document.getElementsByClassName('array-element');
for(let i = 0; i < arrayElements.length; i++) {
arrayElements[i].style.backgroundColor = 'red';
}
}
return (
<div>
<div className="array-container">
{arr.map((value, idx) => (
<div className="array-element"
key={idx}
style={{height: `${value}px`,
weight: `${value}px`,
margin: '1px 1px',
backgroundColor: 'blue'}}
></div>))
}
</div>
<div>
<button onClick={() => changeColor()}>change-color!</button>
<button onClick={() => generateArray()}>new-array</button>
</div>
</div>
);
}
export default Dummy2;
EDIT: I manage to fix this by adding the following function
const resetColors = () => {
const arrayBars = document.getElementsByClassName('array-element');
for(let i = 0; i < arrayBars.length; i++) {
arrayBars[i].style.backgroundColor = 'blue';
}
}
I called it whenever the array is reset.
But still I don't understand why the styling is kept.