Search code examples
cssreactjsgriddle

Selecting a Row in React Griddle, and changing tr background color


I'm just wondering if someone has already been able to change the color of a row, in React Griddle, by clicking on it (just once).

I'm experimenting things with JQuery, and even with Griddle Metadata, but it may be done in a cleaner way ?

Edit : I'm using React 15, Griddle inside MantraJS/Meteor, getting the data in my react Component using a Mantra container.

I can get the data by using onClick event, but not able to switch the background color in the onClick event, or playing with Metadatas.

Thanks !

EDIT : I use another view to display the content of the table, so for now I don't need to change the background of my tables cells, but if I found a solution I'll complete this post


Solution

  • You can use react-griddle props rowMetadata and onRowClick to do this:

    class ComponentWithGriddle extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          selectedRowId: 0,
        };
      }
      onRowClick(row) {
        this.setState({ selectedRowId: row.props.data.id });
      }
      render() {
        const rowMetadata = {
          bodyCssClassName: rowData => (rowData.id === this.state.selectedRowId ? 'selected' : ''),
        };
        return (
          <Griddle
            ...
            rowMetadata={rowMetadata}
            onRowClick={this.onRowClick.bind(this)}
          />
        );
      }
    }
    

    Now this adds a selected class to the selected <tr> elements, so you can use custom styles to add colors or whatever styles you want to apply to the selected row.

    Note that a more convenient API for selecting rows has been called for in the Griddle Github issues.