Home > Enterprise >  Removing a specific element in an array with React
Removing a specific element in an array with React

Time:04-20

I have this code

I have some sections and inside it I have an item, number and button. How can I remove some specific item?

I'm rendering the sections as:

{sections.map((section, index) => (
        <Section
          section={section}
          key={section.id}
          addItem={(item) => addItem(index, item)}
          removeItem={(i) => removeItem(index, i)}
        />
      ))}

And in my Section component, I'm rendering it as:

{section.items.map((item, i) => (
        <>
          <h2>{item}</h2>
          <h3>{section.number[i]}</h3>
          <button onClick={() => removeItem(i)}>Remove</button>
        </>
      ))}

The remove function is in the Section's parent component and is:

const removeItem = (index, i) => {
    let filteredItem = sections[index].items.splice(i);
    let filteredNumber = sections[index].number.splice(i);

    setSections((prev) => ({ ...prev, filteredItem, filteredNumber }));
  };

When I click the remove button it says that sections.map is not a function. What am I doing wrong?

CodePudding user response:

At glance looks like you have an error in your Section component. The code:

{section.items.map((item, i) => (
    <>
        <h2>{item}</h2>
        <h3>{section.number[i]}</h3>
        <button onClick={() => removeItem(i)}>Remove</button>
    </>
))}

should be:

{section.items.map((item, i) => (
    <>
        <h2>{item.title}</h2>
        <h3>{item.number[i]}</h3>
        <button onClick={() => removeItem(i)}>Remove</button>
    </>
))}

Because you're passing down item and you're trying to render everything in the item object and section.number should be item.number.

CodePudding user response:

I see your problem. In the code below when removing an element you are setting the sections to a single object not an array anymore. so map() doesn't exist on an Object. You have to convert it back into an Array.

const removeItem = (index, i) => {
let filteredItem = sections[index].items.splice(i);
let filteredNumber = sections[index].number.splice(i);
setSections((prev) => ({ ...prev, filteredItem, filteredNumber }));
};
  • Related