Search code examples
javascriptreactjsreact-hookssetstatereact-table

Showing error whenever optional props are being sent to a child component


I am trying to optional have row-select features and this should be determined based on a prop that is being passed from parent. I have two grids on a single page, where in one has prop that should enable row selection and the other one does not. But I am getting this error "Cannot read property 'className' of undefined " .

Sandbox: https://codesandbox.io/s/react-table-row-table-alternate-single-row-working-5fr81

import * as React from "react";
import { render } from "react-dom";
import DataGrid from "./DataGrid";
import ShowMore from "./ShowMore";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      columns: []
    };
  }

  componentDidMount() {
    this.getData();
    this.getColumns();
  }

  getData = () => {
    const data = [
      { firstName: "Jack", status: "Submitted", items: [1, 2, 3, 4] },
      { firstName: "Simon", status: "Pending", items: [1, 2] },
      { firstName: "Syls", status: "Pending", items: [1] },
      { firstName: "Pete", status: "Approved", items: [] }
    ];
    this.setState({ data });
  };

  getColumns = () => {
    const columns = [
      {
        Header: "First Name",
        accessor: "firstName"
      },
      {
        Header: "Status",
        accessor: "status"
      },
      {
        Header: "Items",
        accessor: "items",
        Cell: row => <ShowMore value={row.value} />
      }
    ];
    this.setState({ columns });
  };

  onClickRow = rowInfo => {
    this.setState({ allData: rowInfo }, () => {
      console.log(this.state.allData);
    });
  };

  render() {
    return (
      <>
        <DataGrid
          data={this.state.data}
          columns={this.state.columns}
          rowClicked={this.onClickRow}
        />
        <DataGrid data={this.state.data} columns={this.state.columns} />
      </>
    );
  }
}


Solution

  • In your onRowClick function in DataGrid.js, your function will return nothing on first render (or until something is clicked). ReactTable is expecting SOMETHING here. If you supply an empty object, it will successfully render.