Junior — Senior
Debugging a React component: fixing list logic
livecode
Task condition
In this exercise, you are required to analyze a React component that displays array elements and their squares, and also allows adding and removing elements via buttons. The current code contains several logical errors, which cause the list state and the calculated sum to work incorrectly.
Requirements
- The component displays a list of numbers and their squared values.
- The Add button should add the number entered by the user to the array.
- The delete button should remove the selected element from the array.
- Clicking the sort button changes the display order (ascending/descending).
- Additional: display a tooltip above the sort icon.
- Additional: calculate and display the sum of the squares of all elements.
Original code
import "./styles.css";
import React from "react";
import orderBy from "lodash/orderBy";
const ascIcon = "↑";
const descIcon = "↓";
/*
* Component that renders list elements and their squared values,
* The add button should add a value to the array
* The delete button should remove a value from the array
*
* Task — change the functionality
* Additional task: get the tooltip text from the title attribute.
* Additional task: calculate the sum of squares.
*/
export default function App() {
let array = [1, 2, 3, 4, 5, 6];
const [sortDirection, setSortDirection] = React.useState<any>("asc");
const [inputValue, setInputValue] = React.useState("");
let sum = 0;
array.map(i => (sum += i * i));
const handleChangeInput = (e: React.FormEvent<HTMLInputElement>) => {
setInputValue(e.currentTarget.value);
};
const handleAddItem = () => {
array.push(Number(inputValue));
};
const handleRemoveItem = (id: number) => {
array = array.filter((item) => item !== id);
};
const handleChangeSort = () => {
const newSorting = sortDirection === "asc" ? "desc" : "asc";
setSortDirection(newSorting);
};
return (
<div className="App">
<input value={inputValue} onChange={handleChangeInput} />
<button onClick={handleAddItem}>Add</button>
<button onClick={handleChangeSort} title={sortDirection === "asc" ? "Sort descending" : "Sort ascending"}>
{sortDirection === "asc" ? ascIcon : descIcon}
</button>
{orderBy(array, undefined, sortDirection).map((i) => {
return (
<div key={i}>
{i} {i * i}
<button onClick={() => handleRemoveItem(i)}>delete</button>
</div>
);
})}
<span>Sum of squares: {sum}</span>
</div>
);
}
``