I'm currently working on a visualizer for sorting algorithms where there are colorful bars that will animate when a specific sorting algorithm is triggered by clicking the play button.
To achieve this, I created an array of div elements representing the bars and set their background colors. Additionally, I made another array to keep track of the lengths of the bars so that when I sort the length array, the corresponding bar array gets sorted as well.
const {bars, setBars} = useContext(BarsContext)
const [data, setData] = useState([])
useEffect(() => {
setData([])
setBars([])
for(let i=0; i<=value; i++){
const randomLength = Math.floor(Math.random() * 500)
setBars(current => [...current, <div className="bar" ref={ref} style={{ height: randomLength, backgroundColor: "#add8e6" }}></div>])
setData(data => [...data, randomLength])
}
}, [value])
const runAlgorithm = () => {
if(active == "bubble"){
bubbleSort()
} else if(active == "merge"){
Mergsort()
} else if(active == "selection"){
Selectionsort()
}
}
const sleep = ms => new Promise(r => setTimeout(r, ms));
const bubbleSort = async() => {
let count = 0
console.log(data)
for(let i=0; i<bars.length; i++){
for(let j=0; j<bars.length; j++){
console.log(bars[j].props.style.backgroundColor)
bars[j].props.style.backgroundColor = "red"
bars[j+1].props.style.backgroundColor = "red"
if(data[j] > data[j+1]){
let temp = data[j+1]
data[j+1] = data[j]
data[j] = temp
setData([...data])
let temp2 = bars[j+1]
bars[j+1] = bars[j]
bars[j] = temp2
setBars([...bars])
await sleep(100);
}
count +=1
console.log(count)
}
}
console.log(data)
}
When implementing the sorting algorithm, I encountered an issue trying to change the background color of the bars to red. Despite logging the properties successfully, an error message indicating undefined props was displayed.