0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Reactで簡単なテーブルを作る

Posted at

React で Tableを作る

シンプルな HTML Table

HTMLTableを作りたい場合、thtrで囲み、trtableで囲みます。
例:

<table>
  <tr>
    <th>7</th>
    <th>8</th>
    <th>9</th>
  </tr>
  <tr>
    <td>7*7=49</td>
    <td>7*8=56</td>
    <td>7*9=63</td>
  </tr>
  <tr>
    <td>7*8=56</td>
    <td>8*8=64</td>
    <td>9*8=72</td>
  </tr>
  <tr>
    <td>7*9=63</td>
    <td>8*9=72</td>
    <td>9*9=81</td>
  </tr>
</table>

それをReact Componentに変えると

function KuKuTable(){
  return(
    <table>
      <tr>
        <th>7</th>
        <th>8</th>
        <th>9</th>
      </tr>
      <tr>
        <td>7*7=49</td>
        <td>7*8=56</td>
        <td>7*9=63</td>
      </tr>
      <tr>
        <td>7*8=56</td>
        <td>8*8=64</td>
        <td>9*8=72</td>
      </tr>
      <tr>
        <td>7*9=63</td>
        <td>8*9=72</td>
        <td>9*9=81</td>
      </tr>
    </table>
  )
}

になります。

別々のコンポーネントに分割します

Table コンポーネントを TableHeader と TableBody コンポーネントで構成する
それぞれを書きます。

function Table() {
  return (
    <table>
      <TableHeader />
      <TableBody />
    </table>
  );

Tbody はいくつの Tr から作られた、またTrはいくつの Td から作られた、Td はその乗算の式。

function TableBody() {
  const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  const equation = (base: number, multiplier: number) => `${base} * ${multiplier} = ${base * multiplier}`;
  const Tbody = (arrayJsx: JSX.Element[]) => <tbody>{arrayJsx}</tbody>;
  const Tr = (arrayJsx: JSX.Element[]) => <tr>{arrayJsx}</tr>;
  const Td = (equation: string) => <td>{equation}</td>;

  const result =
    Tbody(numbers.map((num, idx) =>
      Tr(numbers.map(num2 =>
        Td(equation(num, num2))))));
        
  return result;
}
function TableHeader() {
  return (
    <thead>
      <tr>
        {[1, 2, 3, 4, 5, 6, 7, 8, 9].map(num => <th key={"th" + num}>{num}</th>)}
      </tr>
    </thead>
  );
}

最後はpage.tsxで使います。

export default function Home() {
  return (
    <div className="m-10">
      <Table />
    </div>
  );
}

image.png
出来上がり!

0
2
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?