I am writing a function inside of a React component to hide/show columns in a table. The table is generated from an imported config object containing objects which model the column data. We render by simply mapping over the table content and rendering cells based on the columns. The method I'm writing exists in the table component and accepts a string corresponding to the targetProp property inside of a column object. Additionally, the table needs to render a child component which serves as an actual toggle menu.

  toggleTableColumn(targetProp: string) {
    const allColumns = tableConfigMap[this.configName].columns; //an array of all column objects available for display
    const targetColumnIndex = _.findIndex(allColumns, { targetProp }); // original index of target column, used for re-inserting in correct order
    const targetColumn = allColumns[targetColumnIndex]; 
    const displayedColumns = [...this.tableConfig.columns];

    const columnShown = !_.isUndefined(_.find(displayedColumns, { ...targetColumn }));

    if (columnShown) {
      const adjustedColumns = _.without(this.tableConfig.columns, targetColumn);
      this.tableConfig = { ...this.tableConfig, columns: adjustedColumns };
    } else {
      const adjustedColumns = displayedColumns;
      adjustedColumns.splice(targetColumnIndex, 0, targetColumn);
      this.tableConfig = { ...this.tableConfig, columns: adjustedColumns };

I'm feeling like there must be a more elegant way to do this. I'm attempting not to add some kind of isVisible prop to the table column objects as it seems wrong to put this kind of view logic into the data model.

The child component menu will contain a dropdown list of all the columns with checkboxes corresponding to visible/invisible columns. It seems to me like not only would I have to pass this toggle function to the menu component, I'd also have to pass the list of all columns AND the list of selected columns as props to the menu component in order to properly render the checkbox styles (checked or unchecked).

This feels very sloppy, there must be a more elegant way. I hope this makes sense.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.