Style cell in react-datasheet-grid

894 views Asked by At

I came across a very nice package called react-datasheet-grid. I want to color a specific cell depending on it's value. When I build the table (data-sheet) I do it with an array of columns as the doc says. When I want to style it there are examples only for styles the whole table. I want to style a specific cell but I don't know how to reach it.

2

There are 2 answers

1
Vbuongi On

You can assign classNames within the cell object. Please see the [hopefully?] complete example below:

import ReactDataSheet from 'react-datasheet';
import React, { useState } from "react"; 

export default function DataSheetExample() {

    let tableContent= [
        [   
            {
                value:  "Something I want to style", 
                className : "my-style"
            },
            {
                value:  "Something else that I will style",
                className : "my-style"
            }
        ],
        [{value:  5}, {value:  5}]
        ]

    const [dataSheetGrid, setDataSheetGrid] = useState(tableContent);

    return (
        <ReactDataSheet
            data={tableContent}
            valueRenderer={cell => cell.value}
            onCellsChanged={changes => {
                const grid = dataSheetGrid.map(row => [...row]);
                changes.forEach(({ cell, row, col, value }) => {
                    grid[row][col] = { ...grid[row][col], value };
                });
                setDataSheetGrid(grid)
            }}
        />
    );
  }

In this example, you would need to add the declared class to your CSS styling sheet. Here is my source in case you have follow-up questions - https://github.com/romanstan1/react-datasheet-header.

Note that if you plan to boilerplate the example, you will need to pass tableContent in via props.

0
Hussam Khatib On

You can use cellClassName prop to achieve it.
https://react-datasheet-grid.netlify.app/docs/api-reference/columns/#cellclassname

<DataSheetGrid
  value={data}
  onChange={setData}
  columns={columns}
  cellClassName={({ rowData, rowIndex, columnId }) => {
     if(rowData.firstName === 'Alice'){
        return 'bg-red' // a class defined in our stylesheet
     }            
  }}
/>