Search code examples
javascriptreactjsblueprintjs

Render table row by key from list of objects


I'm trying to bind my data to a blueprint.js Table , however the docs are unclear on how to do this. How do I create a custom render function for a blueprint.js Table to render the key from a list of objects?

In the example rowIndex is passed by default.

The code:

data = [
  { name: "L/S", col2: "abc" }, 
  { name: "HY", col2: "def" }
];

myRender = (rowIndex: number, key: string) => {
  return <Cell> {this.data[rowIndex][key]} </Cell>;
};

<Table numRows={2}>
  <Column name="not-working" cellRenderer={this.myRender("name")} />
  <Column name="not-working2" cellRenderer={this.myRender("col2")} />
</Table>;

The error:

TypeError
Cannot read property 'undefined' of undefined

  18 | 
  19 | myRender = (rowIndex: number, key: string) => {
> 20 |   return <Cell> {this.data[rowIndex][key]} </Cell>;
     |                                     ^
  21 | };

See example here: https://codesandbox.io/s/k9l9q2150r

The docs: https://blueprintjs.com/docs/#table.basic-usage


Solution

  • cellRenderer expects a function which takes a rowIndex as an argument. So this is what you need to do:

    myRender = (key: string) => (rowIndex: number) => {
      return <Cell>{this.data[rowIndex][key]}</Cell>;
    };
    

    And here's the sandbox