Home > Software design >  Add and remove items by index when pushed into state array with other array data React
Add and remove items by index when pushed into state array with other array data React

Time:11-09

I want to remove items from an array that are pushed into a state array. I can add but the remove is slightly confusing for me in terms of react. Current remove function does not work as it removes all, but the first element? I only want to be able to remove the added data e.g. 5,6,7,8

Stackblitz: https://react-ts-p6iwoh.stackblitz.io

Code so far:

import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';

interface Idata {
  name: string;
  values: number[];
}

const initialData: Idata[] = [
  {
    name: 'Title 1',
    values: [98, 15, 7, 8],
  },
  {
    name: 'Title 2',
    values: [44, 5, 7, 8],
  },
  {
    name: 'Title 3',
    values: [5, 7, 8, 9],
  },
  {
    name: 'Title 4',
    values: [76, 88, 9, 5],
  },
];

const addData: Idata[] = [
  {
    name: 'Title 5',
    values: [98, 15, 7, 8],
  },
  {
    name: 'Title 6',
    values: [44, 5, 7, 8],
  },
  {
    name: 'Title 7',
    values: [5, 7, 8, 9],
  },
  {
    name: 'Title 8',
    values: [76, 88, 9, 5],
  },
];

const App: React.FunctionComponent = () => {
  const [tag, setTag] = React.useState<Idata[]>(initialData);

  return (
    <React.Fragment>
      <div className="intial-data">
        {tag?.map((inner: Idata, index: number) => {
          return <div key={index}>{inner.name}</div>;
        })}
      </div>
      <br />
      <div>
        {addData?.map((inner: Idata, index: number) => {
          return (
            <React.Fragment key={index}>
              <div>
                {inner.name}{' '}
                <button
                  onClick={() =>
                    setTag((oldArray) => [...oldArray, addData[index]])
                  }
                >
                  Add
                </button>
                <button
                  onClick={() =>
                    setTag((oldArray) => oldArray.splice(index, 1))
                  }
                >
                  Remove
                </button>
              </div>
            </React.Fragment>
          );
        })}
      </div>
    </React.Fragment>
  );
};

render(<App />, document.getElementById('root'));

CodePudding user response:

With regards to the comments below:

After you add an id to IData, you could use filter, like:

onClick={() =>
    setTag((oldArray) => {
        return oldArray.filter(item => item.id !== inner.id);
    })
}
  • Related