테이블에서 열 순서 이동하기

miin·2023년 10월 5일
0

Skill Collection [Function]

목록 보기
40/46
post-thumbnail
  const upDownBtn = (type: string) => {
    if (checkList.length > 0) {
      //원본 배열을 복사함
      const updatedList = [...valueList] 
      //이동할 객체 배열로 추출
      const [movedItem] = updatedList.splice(selectChecked, 1)

      if (type === 'up') {
        //첫번째 줄이면 맨 마지막으로 보냄
        const newIndex = selectChecked - 1 < 0 ? valueList.length - 1 : selectChecked - 1 
        // 이동할 인덱스에 이동하려던 객체값으로 변경
        updatedList.splice(newIndex, 0, movedItem) 
        //체크 인덱스 변경
        setSelectChecked(newIndex)
        //이동할때마다 체크도 따라와야하기 때문에 체크리스트 함께 변경
        setCheckList([newIndex])
      }

      if (type === 'down') {
        //마지막 줄이면 맨 첫번째로 보냄
        const newIndex = selectChecked === valueList.length - 1 ? 0 : selectChecked + 1
        updatedList.splice(newIndex, 0, movedItem) 
        setSelectChecked(newIndex)
        setCheckList([newIndex])
      }
	
      //원본 배열 변경
      setValueList(updatedList)
      return
    }
    alert('체크박스를 선택해주세요.')
  }
  
return(
  <thead>
  ...생략
  </thead>
  <tbody>
	<RowStyle 
  	 className="inputContainer"
     key={index}
     isChecked={selectChecked === index}>
	</RowStyle>
  ...생략
  <tbody>
    <div>
      <ul>
       <li style={{ cursor: 'pointer' }} onClick={() => upDownBtn('down')}>
          <DownBtn width={35} height={35} />
       </li>
       <li style={{ cursor: 'pointer' }} onClick={() => upDownBtn('up')}>
         <UpBtn width={35} height={35} />
       </li>
    </div>
)  
    
const RowStyle = styled.tr<{ isChecked: boolean }>`
  background-color: ${({ isChecked }) => (isChecked ? '#e2eaf7' : 'white')};
`

0개의 댓글