React

[React] useState 리스트에서 index로 요소 제거하기

캐럿노트 2023. 7. 22. 21:59

splice

splice 함수를 사용하여 제거

 array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

start

- 배열의 변경을 시작할 index

 

deleteCount

- 배열에서 제거할 개수

- 0일 경우 제거하지 않는다. (이 경우 최소한 하나의 새로운 요소를 추가해야한다.)

 

item1, item2...(Oprional)

- 배열에 추가할 요소

- 생략할 경우 요소를 제거하기만 한다

 

Return

- 제거한 요소를 담은 배열

- 아무것도 제거하지 않을 경우 빈 배열을 반환

 

Code

import React, { useState } from 'react';

function MyComponent() {
  const [myArray, setMyArray] = useState(['item1', 'item2', 'item3', 'item4']);

  const removeItem = (indexToRemove) => {
    // 배열에서 해당 인덱스의 요소를 제거
    const updatedArray = [...myArray];
    updatedArray.splice(indexToRemove, 1);
    setMyArray(updatedArray);
  };

  return (
    <div>
      <ul>
        {myArray.map((item, index) => (
          <li key={index}>
            {item}
            <button onClick={() => removeItem(index)}>Remove</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default MyComponent;

 

 

참고

블로그

https://tocomo.tistory.com/31

 

MDN

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/splice