React 動的テーブル行

動作テスト

 

import { useState } from "react";

function FlexibleRowTableTest() {

    const[line, setLine] = useState<number[]>([]);
    const[count, setCount] = useState<number>(1);

    // 行の追加
    const addRow = () => {
        setLine([...line, count]);
        setCount(count + 1);
      }

    // 上へ
    const upRow = (i: number) => {
        if (0 < i) {
            setLine((prevState) => {
                const tempValue: number = prevState[i];
                const tempLine = prevState.filter((item, j) => (j !== i));
                tempLine.splice(i-1, 0, tempValue);
                return tempLine; 
            });
        }
    }

    // 下へ
    const downRow =(i: number) => {
        if (i < line.length-1) {
            setLine((prevState) => {
                const tempValue: number = prevState[i];
                const tempLine = prevState.filter((item, j) => (j !== i));
                tempLine.splice(i+1, 0, tempValue);
                return tempLine; 
            });
        }
    }

    // 行の削除
    const deleteRow = (i: number) => {
        setLine(line.filter((item, j) => (j !== i)));
    }

    return (
        <table>
            {line.map((item: number, i: number)=>(
                <tr>
                    <td>{item}</td>
                    <td><button onClick={() => upRow(i) }>上へ</button></td>
                    <td><button onClick={() => downRow(i) }>下へ</button></td>
                    <td><button onClick={() => deleteRow(i) }>行削除</button></td>
                </tr>
            ))} 
        <button onClick={addRow}>行追加</button>
        </table>
    )
}

export default FlexibleRowTableTest;

 

投稿日: