2 - Dynamic List of Items with Strikethrough
Description
This puzzle requires you to build a React application that displays a dynamic list of items. Each item should have its own text and the ability to be crossed out through a strike-through effect when clicked. Users should be able to add new items to the list and clear all existing items at once.
Algorithm
State Management: Utilize React's
useState
hook to manage two state variables:items
: An array containing objects representing each list item with properties like text andisStrikedThrough
flag.newText
: A string representing the text of the new item to be added.
Adding Items: Define a function that takes the
newText
as input and updates theitems
state with a new object containing the new text and an initialisStrikedThrough
value offalse
.Striking Through Items: Define a function that takes the index of the clicked item as input and updates the
isStrikedThrough
property of the corresponding item in theitems
state totrue
.Clearing All Items: Define a function that resets the
items
state to an empty array.Conditional Rendering: Based on the
isStrikedThrough
value of each item, apply the styling for strikethrough text (e.g.,text-decoration: line-through
) when rendering the list items.
Code
DynamicListApp.ts
Explanation
useState Hooks: Two state variables,
items
andnewText
, are used to manage the list items and the text for the new item.Adding Items: The
handleAddItem
function is triggered when the "Add Item" button is clicked. It checks ifnewText
is not empty, and if so, creates a new object with the text and adds it to theitems
state using the spread operator.Striking Through Items: The
handleStrikeThrough
function accepts the index of the clicked item. It creates a copy of theitems
array, flips theisStrikedThrough
flag of the clicked item, and sets the state with the updated array.Clearing All Items: The
handleClearAll
function simply resets theitems
state to an empty array.Conditional Rendering: The
map
function iterates over theitems
array and applies thestriked-through
class to list items with theisStrikedThrough
flag set totrue
.
Additional Notes
This code provides a basic implementation of the dynamic list functionality. You can further enhance it by adding features like:
Persisting the list data in local storage to survive reloads.
Prioritizing or reordering list items.
Implementing different styles for struck-through items.
Last updated