Reputation: 35
I am using reactjs to create a sorting algorithm visualizer.After the function bubblesort is called, useState updates the list thus triggering a re-render.But the new list is not injected to the dom. The implementation is done using (functional components) and some hooks. -A newbie in react
Below is the code snippet
import React, { useEffect, useState } from 'react';
const ArrayBars = ()=>{
const [list, setlist] = useState([]);
function BubbleSort(){
let arr=list
for(var i=0;i<arr.length-1;i++){
for(var j=i+1;j<arr.length;j++){
if(arr[i] > arr[j]){
let temp = arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
setlist(arr)
}
// Generate an array:
function generatearray(){
const sliderValue=document.getElementById('slide').value;
const arr = []
for(let i=0;i<sliderValue;i++){
const Bar_height = Math.floor(Math.random() * (760 - 400 + 1) ) + 400;
arr.push(Bar_height);
}
setlist(arr);
}
return(
<div>
<div className="header mt-4 p-3 mb-3">
<div className="slider">
<label>array Size :</label>
<input type="range" min="10" max="100" id="slide" ></input>
<button type="button" className="btn btn-success" onClick={generatearray}>Generate array</button>
</div>
<div className="btns">
<button type="button" className="btn btn-outline-info p-3" onClick={BubbleSort}>Bubble Sort</button>
<button type="button" className="btn btn-outline-info p-3">Selection Sort</button>
<button type="button" className="btn btn-outline-info p-3">Insertion Sort</button>
<button type="button" className="btn btn-outline-info p-3">Merge Sort</button>
<button type="button" className="btn btn-outline-info p-3">Quick Sort</button>
</div>
</div>
<div className="array px-5 d-flex justify-content-center">
{
list.map((height,idx)=>{
return(
<div id={idx} className="bars" style={{height:`${height}px`}}></div>
)
})
}
</div>
</div>
)
}
export default ArrayBars;
Upvotes: 2
Views: 72
Reputation: 202618
You are mutating the list
state object and saving it back into state, so the list
array reference never changes and React bails on rerendering.
Shallow copy it first, then update it.
function BubbleSort(){
let arr = [...list]; // <-- shallow copy state array
for (let i = 0; i < arr.length - 1; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
setlist(arr)
}
Fun fact: You can swap two array elements in a single line using array destructuring assignment.
[arr[j], arr[i]] = [arr[i], arr[j]];
Upvotes: 3