Search code examples
reactjsgriddle

How to change row class based on the cells' values in griddle-react?


I have a table in griddle (v 1.13.1) and I want to highlight some rows.

var data = [{highlight:true, name:"Abc"},
            {highlight:false, name:"Abc"},
            {highlight:true, name:"Abc"}]

<Griddle 
   data={data} />

I want to add class to all rows, which have highlight==true. How can I do that?


Solution

  • If you look at the source code of how <Row> component is implemented, you can then define your own. The component accepts a components props, and you can add there your own logic there as I did in the below demo.

    var data = [
      { highlight: true, name: "Abc" },
      { highlight: false, name: "Abc" },
      { highlight: true, name: "Abc" }
    ];
    
    const TableRow = ({
      Cell,
      griddleKey,
      columnIds,
      onClick,
      onMouseEnter,
      onMouseLeave,
      style,
      className,
      rowData
    }) => {
      const appliedClassName = rowData.highlight
        ? `${className} my-own-class`
        : className;
      return (
        <tr
          key={griddleKey}
          onClick={onClick}
          onMouseEnter={onMouseEnter}
          onMouseLeave={onMouseLeave}
          style={style}
          className={appliedClassName}
        >
          {columnIds &&
            columnIds.map(c => (
              <Cell
                key={`${c}-${griddleKey}`}
                griddleKey={griddleKey}
                columnId={c}
                style={style}
                className={className}
              />
            ))}
        </tr>
      );
    };
    
    function App() {
      return (
        <div className="App">
          <Griddle
            components={{
              Row: props => <TableRow {...props} />
            }}
            data={data}
          />
        </div>
      );
    }
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);
    <script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
    <script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/griddle-react/0.8.2/Griddle.min.js"></script>
    
    <div id="root"></div>

    Note: For some reason this code doesn't work in SO editor.