How to allow users to click on rows

316 views Asked by At

I'm using griddle-react in order to display a table. I'm having trouble making each cell clickable. For now I'd like to just print the id value to the console. Here is my code:

import React from "react";
import ReactDOM from "react-dom";
import Griddle, { plugins } from "griddle-react";

import "./styles.css";

const styleConfig = {
  icons: {
    TableHeadingCell: {
      sortDescendingIcon: <small>(desc)</small>,
      sortAscendingIcon: <small>(asc)</small>
    }
  },
  classNames: {
    Row: "row-class"
  },
  styles: {
    Filter: { fontSize: 18 },
    NextButton: {}
  }
};

export default class App extends React.Component {
  getData() {
    var data = [
      {
        id: 0,
        name: "Mayer Leonard",
        city: "Kapowsin",
        state: "Hawaii",
        country: "United Kingdom",
        company: "Ovolo",
        favoriteNumber: 7
      },
      {
        id: 1,
        name: "Mayer Leonard",
        city: "Kapowsin",
        state: "Hawaii",
        country: "United Kingdom",
        company: "Ovolo",
        favoriteNumber: 7
      }

    ];
    return data;
  }

  constructor() {
    super();
    this.state = {
      data: this.getData(),
      selectedRowId: 0
    };
    this.onRowClick = this.onRowClick.bind(this);
  }

  onRowClick(row) {
    this.setState({ selectedRowId: row.props.data.id });
    console.log("SELECTED");
  }

  render() {
    const { data } = this.state;
    const rowMetadata = {
      bodyCssClassName: rowData =>
        rowData.id === this.state.selectedRowId ? "selected" : ""
    };
    return (
      <Griddle
        styleConfig={styleConfig}
        data={data}
        plugins={[plugins.LocalPlugin]}
        rowMetadata={rowMetadata}
        onRowClick={this.onRowClick}
      />
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

As you can see, I only have two records in my table with different id's. So if I click anywhere on the first row, I'd like to print the value "0" which is the id and for the second row, I'd like to print the value "1". Any help would be great!

2

There are 2 answers

0
Hemadri Dasari On

Perhaps Try this

  onRowClick(event) {
      this.setState({ selectedRowId: event.target.id });
  }
0
Andrea Pace On

You can use a RowEnhancer to accomplish your needs, in the case below I'm goin to console log the id of the clicked row

  <Griddle
    styleConfig={styleConfig}
    data={data}
    plugins={[plugins.LocalPlugin]}
    rowMetadata={rowMetadata}
    components={{
    RowEnhancer: OriginalComponent => props => (
     <OriginalComponent
        {...props}
        onClick={() => console.log(data[props.griddleKey].id)}
     />
   )}}>