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:

  1. List of Items: We need to create a list of items to display. Each item will have a checkbox and a delete button.

  2. Checkboxes: When a checkbox is checked, it should trigger the display of the delete button for that specific item.

  3. 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:

  1. We create a ListItem component that takes text (item name) and onDelete (callback function) as props.

  2. Inside the ListItem, we use state to manage the checked state of the checkbox using the isChecked state variable.

  3. When the checkbox is checked or unchecked, the handleCheck function is called, toggling the value of isChecked.

  4. 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.

  5. In the App component, we manage the list of items using the items state variable. We pass each item and the handleDelete function as props to the ListItem component.

Did you find this article valuable?

Support Insightful Bytes by becoming a sponsor. Any amount is appreciated!