I created a visualization tool for sorting algorithms that displays vertical bars with varying heights and sorts them. The "Generate new Array" button triggers a function to generate a new array each time it's clicked, which is also used in the componentDidMount() function. How can I change the style property of these bars when the button is clicked? I attempted to select all elements with the class name 'array-bars', store them in an array, and then loop through to change their style properties, but it was unsuccessful. Here is the relevant code snippet:
{ // 'array' is a constant array storing numbers; it's the only state of this program.
array.map((value, idx) => (
<div
className="array-bar"
key={idx}
style={{ height: value, backgroundColor: 'turquoise' }}></div>))
}
componentDidMount(){
this.resetArray();
}
// This function is called when 'generate new array' button is clicked
resetArray(){
const array = [];
for (let i = 0; i < 300; i++) {
array.push(randomIntFromInterval(15, 650));
}
const arrayBars = document.getElementByClassName('array-bar');
for (let i = 0; i < arrayBars.length; i++)
arrayBars[i].style.backgroundColor = 'green'; //this is failing
this.setState({ array });
}
Edited:
Below is the function where I successfully changed the style properties using the method outlined in the previous section.
Also, I need assistance on how to change colors during the mergeSort() function at the end of the code snippet. Using this.setState()
at the end alters the color at the beginning only.
mergeSort(){
for(let i=0;i<animations.length;i++){
const arrayBars= document.getElementsByClassName('array-bar');
const colorChange=i%3!==2;
if(colorChange){
const [barOne,barTwo] =animations[i];
const barOneStyle=arrayBars[barOne].style;
const barTwoStyle=arrayBars[barTwo].style;
const color=i%3===0?'red':'turquoise';
setTimeout(()=>{
barOneStyle.backgroundColor=color;
barTwoStyle.backgroudColor=color;
},i*2);
}
else{
setTimeout(()=>{
const[barOne,newHeight]=animations[i];
const barOneStyle=arrayBars[barOne].style;
barOneStyle.height=newHeight+'px';
},i*2)
}
}
}