Basic React Coding Interview Question: Toggle and Delete List Items
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
ListItem
component that takestext
(item name) andonDelete
(callback function) as props.Inside the
ListItem
, we use state to manage the checked state of the checkbox using theisChecked
state variable.When the checkbox is checked or unchecked, the
handleCheck
function is called, toggling the value ofisChecked
.The delete button is displayed only when the checkbox is checked. When the delete button is clicked, the
handleDelete
function is called, removing the corresponding item from the list.In the
App
component, we manage the list of items using theitems
state variable. We pass each item and thehandleDelete
function as props to theListItem
component.