Search code examples
javascriptreactjsecmascript-6setstatereact-table

Duplicate entries inside array of objects: Javascript


I am trying to add entries into an array, the entries being an object that corresponds to the row of a table. Each row is being highlighted by a color once it is selected. Multiple rows can also be selected using Ctrl Key. On each click I am pushing that row info object into the array. It is defined as a SET and same entry is being duplicated when the same row is clicked multiple times. Also I am unable to de-select the one's that are selected.I am using react-table for the data-grid purposes. Can some one help me out here? Help would be really appreciated.

Sandbox: https://codesandbox.io/s/react-table-row-table-final-hor8j

import * as React from "react";
import ReactTable from "react-table";

export default class DataGrid extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedRows: []
    };
  }

  rowClick = (state, rowInfo) => {
    if (rowInfo) {
      let selectedRows = new Set();
      return {
        onClick: e => {
          if (e.ctrlKey) {
            selectedRows = this.state.selectedRows;
            rowInfo._index = rowInfo.index;
            selectedRows.push(rowInfo);
            this.setState({
              selectedRows
            });
          } else {
            selectedRows = [];
            rowInfo._index = rowInfo.index;
            selectedRows.push(rowInfo);
          }
          this.setState(
            {
              selectedRows
            },
            () => {
              console.log("final values", this.state.selectedRows);
              this.props.rowClicked(this.state.selectedRows);
            }
          );
        },
        style: {
          background:
            this.state.selectedRows.some(e => e._index === rowInfo.index) &&
            "#9bdfff"
        }
      };
    } else {
      return "";
    }
  };

  render() {
    return (
      <ReactTable
        data={this.props.data}
        columns={this.props.columns}
        getTrProps={this.rowClick}
      />
    );
  }
}

Solution

  • Here is an updated sandbox to avoid duplicates https://codesandbox.io/s/react-table-row-table-alternate-single-row-working-1itsy

    The solution includes unselecting rows on second click.

    Happy coding:)