Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-data-grid: create column that is based on another column

In react-data-grid how do I create a column that displays values from another column?

I have an array of objects that contain something like the following:

{
    id: 3,
    latitude: 42.101231231,
    longitude: -81.123132
}

My column definition is such:

    this.columns = [
            { key: 'id', name: 'ID' },
                //The coordinates key for this column doesn't exist
            { key: 'coordinates', name: 'Coordinates', formatter: coordinatesFormatter  }
        ];

The formatter:

const coordinatesFormatter = React.createClass({
  render() {
    return (<div>{latitude}, {longitude}</div>);
  }
});

In the formatter how do I access the latitude and longitude properties on the row in order to concatenate them?

As far as I can tell the formatter only has access to the value of its cell, through this.props.value, with no way to access the whole object for the row.

like image 225
Coin_op Avatar asked Feb 09 '17 02:02

Coin_op


1 Answers

Turns out this is a limitation of the component. One work around is documented here: https://github.com/adazzle/react-data-grid/issues/42

It involves adding getRowMetaData: (row) => row to the column definition. This populates this.props.dependentValues on the formatter component.

This feels like a bit of a hack, is there a better way to access the row data in the formatter?

Update

Found a slightly better way. In the rowGetter method set any extra values you need on the row so that you can simply assign them a column by key.

rowGetter(i) {
  let row = this.props.rows[i];
  row.coordinates = row.latitude + ', ' + row.longitude
  return row;
}

<ReactDataGrid rowGetter={this.rowGetter} ... />
like image 73
Coin_op Avatar answered Oct 13 '22 01:10

Coin_op