Basic React Coding Interview Question: Toggle and Delete List Items
I'm a frontend developer with a passion for creating beautiful and intuitive web experiences. I have more than 2 years of experience in designing and developing web applications.
My expertise lies in creating responsive layouts, optimizing website performance and ensuring cross browser compatibility. I'm proficient in user experience design principles and aim to design interfaces that are both visually appealing and easy to use.
In this blog post, we'll explore a basic coding interview question that tests your understanding of React components and state management. We'll break down the question step by step and provide a simple solution in easy-to-understand language.
The Question: You are tasked with creating a simple React component that displays a list of items with checkboxes. Each item should have a corresponding delete button that becomes visible when the checkbox is checked. When the delete button is clicked, the selected item should be removed from the list.
Breaking Down the Question:
List of Items: We need to create a list of items to display. Each item will have a checkbox and a delete button.
Checkboxes: When a checkbox is checked, it should trigger the display of the delete button for that specific item.
Delete Button: Clicking the delete button should remove the corresponding item from the list.
import React, { useState } from "react";
const ListItem = ({ text, onDelete }) => {
const [isChecked, setIsChecked] = useState(false);
const handleCheck = () => {
setIsChecked(!isChecked);
};
const handleDelete = () => {
onDelete(text);
};
return (
<div>
<label>
<input type="checkbox" checked={isChecked} onChange={handleCheck} />
{text}
</label>
{isChecked && <button onClick={handleDelete}>Delete</button>}
</div>
);
};
const App = () => {
const [items, setItems] = useState(["Apple", "Banana", "Cherry"]);
const handleDelete = (item) => {
setItems(items.filter((i) => i !== item));
};
return (
<div>
<h1>Item List</h1>
{items.map((item, index) => (
<ListItem key={index} text={item} onDelete={handleDelete} />
))}
</div>
);
};
export default App;
Explanation:
We create a
ListItemcomponent that takestext(item name) andonDelete(callback function) as props.Inside the
ListItem, we use state to manage the checked state of the checkbox using theisCheckedstate variable.When the checkbox is checked or unchecked, the
handleCheckfunction is called, toggling the value ofisChecked.The delete button is displayed only when the checkbox is checked. When the delete button is clicked, the
handleDeletefunction is called, removing the corresponding item from the list.In the
Appcomponent, we manage the list of items using theitemsstate variable. We pass each item and thehandleDeletefunction as props to theListItemcomponent.


