简体   繁体   中英

How could I pass in props to display only certain columns in my table?

I'm using data in JSON format to be displayed in a table. What is the best approach passing in a prop to only display(or not display) a certain group of columns in a table?

 componentDidMount() {

   fetch('http://localhost:7000/worldStats')
  .then((data) => data.json())
  .then((data) => this.setState( { stats: data } ));
 }

 render(){
 return(

 // Table..
 {this.state.stats.map( (item) => {
 // Items..
   <td>{item.ID}</td>
   <td>{item.CURRENCY}</td>
   <td>{item.NAME}</td>
   <td>{item.GDP}</td>
   <td>{item.POP}</td>
 })}
 )

Considering that you're rendering a table and all you want to do is toggle which columns to display, I think it makes sense to keep all the logic in a single component. This means there is no need to pass props from one component to then next. Instead, we'll just be utilizing the component state.

Consider the following code:

import React from "react";

class Table extends React.Component {
  state = {
    stats: [],
    indexOfFirstExtendedField: 2,
    displayExtendedFields: true
  };

  componentDidMount() {
    const newData = [
      {
        id: 1,
        currency: "USD",
        name: "dollars",
        gdp: "alot",
        pop: "alot"
      },
      {
        id: 2,
        currency: "MEX",
        name: "pesos",
        gdp: "alot",
        pop: "alot"
      }
    ];
    this.setState({
      stats: newData
    });
  }

  toggleDisplay = () => {
    this.setState(prevState => {
      return {
        displayExtendedFields: !prevState.displayExtendedFields
      };
    });
  };

  createTableHeaders = () => {
    const {
      indexOfFirstExtendedField,
      stats,
      displayExtendedFields
    } = this.state;

    if (displayExtendedFields) {
      return Object.keys(stats[0]).map(key => {
        return <th>{key}</th>;
      });
    } else {
      return Object.keys(stats[0])
        .filter((key, index, array) => {
          return array.indexOf(key) < indexOfFirstExtendedField;
        })
        .map(key => {
          return <th>{key}</th>;
        });
    }
  };

  createTableContent = () => {
    const {
      indexOfFirstExtendedField,
      stats,
      displayExtendedFields
    } = this.state;

    if (displayExtendedFields) {
      return stats.map(item => {
        return (
          <tr>
            {Object.values(item).map(value => {
              return <td>{value}</td>;
            })}
          </tr>
        );
      });
    } else {
      return stats.map(item => {
        return (
          <tr>
            {Object.values(item)
              .slice(0, indexOfFirstExtendedField)
              .map(value => {
                return <td>{value}</td>;
              })}
          </tr>
        );
      });
    }
  };

  render() {
    const { stats, displayExtendedFields } = this.state;
    return (
      <div>
        <button onClick={this.toggleDisplay}>
          {displayExtendedFields ? "Collapse" : "Expand"}
        </button>
        <table>
          {stats.length > 0 && this.createTableHeaders()}
          {stats.length > 0 && this.createTableContent()}
        </table>
      </div>
    );
  }
}

export default Table;

The main takeaways here is that we are using two additional state-values to help us determine which fields to display, indexOfFirstExtendedField and displayExtendedFields . This helps us expand and collapse the columns.

Here's the codesandbox too so you can see it in action: https://codesandbox.io/s/v3062w69v0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM