LoginSignup
0
1

More than 5 years have passed since last update.

Reactで追加ノード無しで複数要素をreturnする

Last updated at Posted at 2018-06-18

:writing_hand: Fragments

普通にやるとトップレベルは1つしか返せないので変なノードができがち
import React, { Component } from "react";

const Tabledata = props => {
  return (
    <div>
      <td>{props.col1}</td>
      <td>{props.col2}</td>
    </div>
  );
};

class Table extends Component {
  render() {
    return (
      <table>
        <tbody>
          <tr>
            <Tabledata col1="silence suzuka" col2="special week" />
          </tr>
        </tbody>
      </table>
    );
  }
}

export default Table;

ss.png

そんな時はReact.Fragmentを使う
const Tabledata = props => {
  return (
    <React.Fragment>
      <td>{props.col1}</td>
      <td>{props.col2}</td>
    </React.Fragment>
  );
};

2.png

一応ショートハンドもある、けど現状だとその他ツールが追いついていないのでReact.Fragment使っとけばよさそう
const Tabledata = props => {
  return (
    <>
      <td>{props.col1}</td>
      <td>{props.col2}</td>
    </>
  );
};
因みにarrayみたいな渡し方でもいけるそう
const Tabledata = props => {
  return [<td>{props.col1}</td>, <td>{props.col2}</td>];
};
0
1
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
1