I am new to React development and am currently trying to create a simple web application that visualises the sorting of an array using selection sort. I have App.tsx, and 2 custom components called ArrayComponent.tsx and ArrayBlock.tsx. The current logic I have is the following:
I use a state to store the current locations of each component, where this state is an array of integers. Each array block is assigned an initial ID which is used to index this locations array state. For example, if the first block in the array is initially the number 6, that component will have an id of 0 and locations[0] = 0. If that block is moved to position 2 in the array, then id remains 0, but locations[0] = 2. A state called movers is used with useEffect to trigger the check to see if animation needs to take place, this useEffect is in ArrayBlock.tsx.
The code works fine until a position is swapped more than twice. So if 0 and 2 get swapped, and the block in position 0 is swapped again later, then the block that was moved to position 2 jumps back to its original position at 0 and undergoes the swap instead of what is there currently, which is the block previously in position 2!
I suspect that it has something to do with the way I return the arrayBlock components within ArrayComponent but I can’t seem to crack it – I’ve only really been working with react for about 15 hours at this point.
Here are the main .tsx files:
App.tsx:
import React from 'react';
import './App.css';
import ArrayComponent from './ArrayComponent';
import { useState } from 'react';
const App: React.FC = () => {
const [valueArr, setValueArr] = useState<number[]>([6, 5, 0, 1, 8, 10, 9, 4]);
const [movers, setMovers] = useState<[number, number]>([-1,-1]);
let valueArrCopy = [...valueArr];
type motionPair = [number, number];
const movements: motionPair[] = [];
const updateArr = (i:number, j:number) => {
setValueArr((prevValues) => {
const newValues = [...prevValues];
[newValues[i], newValues[j]] = [newValues[j], newValues[i]];
console.log(newValues)
return newValues;
});
}
const updateCopiedArr = (i: number, j:number) => {
[valueArrCopy[i], valueArrCopy[j]] = [valueArrCopy[j], valueArrCopy[i]];
}
const sortArr = async () => {
let n = valueArr.length;
console.log("SortArr called");
for (let i = 0; i < n; i++) {
let minIndex = i;
for (let j = i + 1; j < n; j++) {
if (valueArrCopy[j] < valueArrCopy[minIndex]) {
minIndex = j;
}
}
if (minIndex !== i) {
updateCopiedArr(minIndex, i);
console.log("updated array is: "+valueArrCopy)
movements.push([minIndex, i]);
}
}
console.log("This is the list of moves: "+movements)
//Now its time to update the movers array every 6 seconds.
for (let k = 0; k< movements.length;k++){
setMovers(movements[k]);
await new Promise((resolve) => setTimeout(resolve,6000));
}
}
return (
<div className="capsule">
<ArrayComponent updateArr = {sortArr} count={valueArr.length} valueArr={valueArr} movers={movers}></ArrayComponent>
</div>
);
}
export default App;
ArrayComponent.tsx:
import { useEffect, useState } from 'react';
import './App.css';
import ArrayBlock from './ArrayBlock.tsx';
interface ArrayCompProp{
count: number;
valueArr: number[];
updateArr: () => Promise<void>;
movers: [number,number];
}
function ArrayComponent({count, valueArr, updateArr, movers}: ArrayCompProp){
const [locationArr, setLocationArr] = useState<number[]>([0,1,2,3,4,5,6,7]);
const updateLocation = (id:number, newLoc:number) =>{
setLocationArr((prevValues) => {
const newValues = [...prevValues];
newValues[id] = newLoc;
console.log(newValues)
return newValues;
});
};
return (
<div className="array-container">
{valueArr.map((value, index) => {
console.log("This is a rerender: "+value+" and this guy has location of "+locationArr[index]);
return (
<ArrayBlock
key={index}
id={index} // Assign id in increasing order starting from 0
location = {locationArr[index]}
updateLocationArr = {updateLocation}
value={value} // Ensure the value is correctly accessed
movers={movers}
/>
);
})}
<button onClick={updateArr}>Perform Sort</button>
</div>
);
}
export default ArrayComponent
ArrayBlock.tsx:
import { useEffect, useState } from 'react';
import './App.css';
import ArrayBlock from './ArrayBlock.tsx';
interface ArrayCompProp{
count: number;
valueArr: number[];
updateArr: () => Promise<void>;
movers: [number,number];
}
function ArrayComponent({count, valueArr, updateArr, movers}: ArrayCompProp){
const [locationArr, setLocationArr] = useState<number[]>([0,1,2,3,4,5,6,7]);
const updateLocation = (id:number, newLoc:number) =>{
setLocationArr((prevValues) => {
const newValues = [...prevValues];
newValues[id] = newLoc;
console.log(newValues)
return newValues;
});
};
return (
<div className="array-container">
{valueArr.map((value, index) => {
console.log("This is a rerender: "+value+" and this guy has location of "+locationArr[index]);
return (
<ArrayBlock
key={index}
id={index} // Assign id in increasing order starting from 0
location = {locationArr[index]}
updateLocationArr = {updateLocation}
value={value} // Ensure the value is correctly accessed
movers={movers}
/>
);
})}
<button onClick={updateArr}>Perform Sort</button>
</div>
);
}
export default ArrayComponent
What is written above sums up my latest attempts at fixing the problem. All my previous solutions led to the current solution above. The animation works so long that a single position is not swapped more than once, so for example, an array [5,4,3,2,1] visualises selection sort nicely since the swaps are (0,4) and (1,3). Even with the code above, the longer it runs the more the visualisation goes whacko and blocks fly all over the place, in the wrong places.
I am new to posting on stackoverflow so if I need to provide more information please let me know !!
Gregory Maselle is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.