LoginSignup
1
0

ReactのMaterialUIでTableにレコードを追加する

Posted at

はじめに

Apr-18-2024 18-40-52.gif

ソースコード

App.tsx
import React, { useState } from 'react';
import { Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, Button } from '@material-ui/core';

interface TableRowData {
  id: number;
  name: string;
  age: number;
}

const initialRows: TableRowData[] = [
  { id: 1, name: '田中 太郎', age: 20 },
  { id: 2, name: '山田 花子', age: 22 },
];

const DynamicTable: React.FC = () => {
  const [rows, setRows] = useState<TableRowData[]>(initialRows);

  const handleAddRow = () => {
    const newRow: TableRowData = {
      id: rows.length + 1,
      name: `新しい名前 ${rows.length + 1}`,
      age: 20 + rows.length,
    };
    setRows([...rows, newRow]);
  };

  return (
    <TableContainer component={Paper}>
      <Table>
        <TableHead>
          <TableRow>
            <TableCell>ID</TableCell>
            <TableCell>名前</TableCell>
            <TableCell>年齢</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {rows.map((row) => (
            <TableRow key={row.id}>
              <TableCell>{row.id}</TableCell>
              <TableCell>{row.name}</TableCell>
              <TableCell>{row.age}</TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
      <Button onClick={handleAddRow} color="primary" variant="contained" style={{ marginTop: 20 }}>
        行を追加
      </Button>
    </TableContainer>
  );
};

export default DynamicTable;
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0