Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
Trying to delete a key and values from an object, but when I try to delete it breaks some functionality

I am trying to create an add div button and a delete div button. When you select a certain div and click delete, I want to delete only that key from the object. The issue is when I delete and then try to create a new div, it doesn't create the new divs anymore...Not sure what i'm doing wrong or why it only kind of works.

import "./styles.css";
import {
  useEffect,
  useState
} from "react";

// The parent component
const App = () => {
  const [textBoxDivs, setTextBoxDivs] = useState({});

  const addNewTextBox = () => {
    const numOfTextBoxDivs = Object.keys(textBoxDivs).length;
    console.log(numOfTextBoxDivs, "num");
    setTextBoxDivs({
      ...textBoxDivs,
      [`div${numOfTextBoxDivs + 1}`]: {
        isSelected: false,
        innerText: "text"
      }
    });
  };

  const selectItem = (e) => {
    const nextState = { ...textBoxDivs
    };
    Object.keys(nextState).forEach((k) => {
      nextState[k].isSelected = false;
    });
    nextState[e.target.id].isSelected = true;
    setTextBoxDivs(nextState);
  };

  const removeSelectedItem = () => {
    const nextState = { ...textBoxDivs
    };
    if (Object.keys(textBoxDivs).length > 0) {
      Object.keys(textBoxDivs).map((key) => {
        if (textBoxDivs[key].isSelected) {
          delete nextState[key];
          return setTextBoxDivs(nextState);
        }
        return null;
      });
    }
  };

  return ( <
    div >
    <
    button onClick = {
      () => addNewTextBox()
    } >
    Click me to create a selectable div <
    /button> <
    button onClick = {
      (e) => removeSelectedItem(e)
    } >
    Click me to delete a selectable div <
    /button> {
      Object.keys(textBoxDivs).length > 0 &&
        Object.keys(textBoxDivs).map((key, index) => {
          return ( <
            div style = {
              {
                border: textBoxDivs[key].isSelected ?
                  "2px solid green" :
                  "unset"
              }
            }
            onClick = {
              (e) => selectItem(e)
            }
            key = {
              index
            }
            id = {
              key
            } >
            {
              textBoxDivs[key].innerText
            } <
            /div>
          );
        })
    } <
    /div>
  );
};

export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

The problem in your code in the function addNewTextBox, specifically in the line

[`div${numOfTextBoxDivs + 1}`]: {

Because it does not necessarily mean that your are adding a new line. In this case, you are assigning a value to (div + number), but sometimes that already exists. For example, of you change that line for a truly unique number, such as date, it works:

const addNewTextBox = () => {
    const numOfTextBoxDivs = Object.keys(textBoxDivs).length;
    console.log(numOfTextBoxDivs, "num");
    setTextBoxDivs({
      ...textBoxDivs,
      [`div${new Date().getTime()}`]: {
        isSelected: false,
        innerText: "text"
      }
    });
  };
about 4 years ago · Juan Pablo Isaza Report

0

Update selectItem() then it works:

const selectItem = (e) => {
    const nextState = { ...textBoxDivs, setTextBoxDivs }; // setTextBoxDivs was missing
    Object.keys(nextState).forEach((k) => {
      nextState[k].isSelected = false;
    });
    nextState[e.target.id].isSelected = true;
    setTextBoxDivs(nextState);
  };
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!