Should every react component be in an individual file?
Asked Answered
P

1

6

They appear to be in the same file in the documentation example: https://facebook.github.io/react/docs/thinking-in-react.html.

How would you break up your components into pages in an instance like this where some of your components are very small?

class ProductCategoryRow extends React.Component {
  render() {
    return (<tr><th colSpan="2">{this.props.category}</th></tr>);
  }
}

class ProductRow extends React.Component {
  render() {
    var name = this.props.product.stocked ?
      this.props.product.name :
      <span style={{color: 'red'}}>
        {this.props.product.name}
      </span>;
    return (
      <tr>
        <td>{name}</td>
        <td>{this.props.product.price}</td>
      </tr>
    );
  }
}

class ProductTable extends React.Component {
  render() {
    var rows = [];
    var lastCategory = null;
    this.props.products.forEach((product) => {
      if (product.name.indexOf(this.props.filterText) === -1 || (!product.stocked && this.props.inStockOnly)) {
        return;
      }
      if (product.category !== lastCategory) {
        rows.push(<ProductCategoryRow category={product.category} key={product.category} />);
      }
      rows.push(<ProductRow product={product} key={product.name} />);
      lastCategory = product.category;
    });
    return (
      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Price</th>
          </tr>
        </thead>
        <tbody>{rows}</tbody>
      </table>
    );
  }
}
Peculiarize answered 23/3, 2017 at 23:23 Comment(0)
T
5

You may not have to put each component in its own file - for example, you could further split the ProductRow component using stateless functional components:

const ProductName = (product) => 
  <span style={{color: product.stocked ? 'black' : 'red'}}>
    { product.name }
  </span>

const ProductRow = (product) => 
  <tr>
    <td>{ ProductName(product) }</td>
    <td>{ product.price }</td>
  </tr>
Tautologize answered 23/3, 2017 at 23:31 Comment(2)
Thanks! Are there general guidelines surrounding what should be an individual file and what should not? Are React classes generally individual files?Peculiarize
Generally, reusable components go into their own files whereas components that are dependent on each other for a specific purpose go in the same fileTautologize

© 2022 - 2024 — McMap. All rights reserved.