Giter Site home page Giter Site logo

Conditionally color rows? about table HOT 22 CLOSED

tanstack avatar tanstack commented on July 19, 2024
Conditionally color rows?

from table.

Comments (22)

nomanalikhan avatar nomanalikhan commented on July 19, 2024 17

This solution is applicable to version 6. Do we have some workaround for version 7?

from table.

reza-ebrahimi avatar reza-ebrahimi commented on July 19, 2024 12

In 2023, This should work:

declare module '@tanstack/react-table' {
    interface TableMeta<TData extends RowData> {
        getRowStyles: (row: Row<TData>) => CSSProperties;
    }
}

interface YourType {
    errorStatus: number;
}

const YourTable = () => {
    const table = useReactTable({
        data,
        columns,
        getCoreRowModel: getCoreRowModel(),
        meta: {
            getRowStyles: (row: Row<YourType>): CSSProperties => ({
                background: row.original.errorStatus === 1 ? "red" : "transparent",
            }),
        }
    });

    return (<div><table><tbody>
        {table.getRowModel().rows.map(row => (
            <tr
                key={row.id}
                style={table.options.meta?.getRowStyles(row)}> // <-- Use it here
                {row.getVisibleCells().map(cell => (
                    <td key={cell.id}>
                        {flexRender(cell.column.columnDef.cell, cell.getContext())}
                    </td>
                ))}
            </tr>
        ))}
    </tbody></table></div>);
}

from table.

tannerlinsley avatar tannerlinsley commented on July 19, 2024 10

from table.

aaroncrawford avatar aaroncrawford commented on July 19, 2024 6

For future, this is a good reference sample on how getTrProps works :
https://codesandbox.io/s/k3q43jpl47

from table.

writes-of-spring avatar writes-of-spring commented on July 19, 2024 4

@smokinjoe if you use the table's meta property, you can access the row data and conditionally style a row

https://codesandbox.io/s/twilight-butterfly-3i964n?file=/src/main.tsx
declaration merging on line 15
defining a custom row style function on line 97
and implementing it on line 126

Hopefully that suits your needs!

from table.

bryan-davis avatar bryan-davis commented on July 19, 2024 3

@reza-ebrahimi Thank you for the example!

To piggyback off the example, he's an example that also works in v8 if someone wanted to make a reusable component and pass getRowStyles to it as a prop.

const YourTable = ({data, columns, getRowStyles}) => {
  const table = useReactTable({
    data,
    columns,
    getCoreRowModel: getCoreRowModel(),
  });

  return (
    <div>
      <table>
        <tbody>
          {table.getRowModel().rows.map(row => (
            <tr
              key={row.id}
              style={typeof getRowStyles === 'function' ? getRowStyles(row) : {}}
            >
              {row.getVisibleCells().map(cell => (
                <td key={cell.id}>
                  {flexRender(cell.column.columnDef.cell, cell.getContext())}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

const getRowStyles = (row) => {
  if (row.original.someCondition) {
    return {
      background: 'red',
    };
  }
};

const data = fetchSomeData();
const columns = [
  // columnDefs
];

return <YourTable data={data} columns={columns} getRowStyles={getRowStyles} />;

from table.

KhaledKassab avatar KhaledKassab commented on July 19, 2024 1

@tannerlinsley How to conditionally color Rows and cells in a functional component, appreciate if you demonstrate with an example.

from table.

zachrnolan avatar zachrnolan commented on July 19, 2024 1

I was able to style rows conditionally by following this guide for v7: https://react-table.tanstack.com/docs/examples/data-driven-classes-and-styles

Example:

getRowProps={row => ({
  style: {
    background: row.original.review_status === 'flagged' ? 'yellow' : 'white',
  },
})}

from table.

lmgroger avatar lmgroger commented on July 19, 2024 1

This was helpful in getting @zachrnolan's solution above to work since that link is broken now:
https://spectrum.chat/react-table/general/v7-row-getrowprops-how-to-pass-custom-props-to-the-row~ff772376-0696-49d6-b259-36ef4e558821?m=MTU2ODM4ODYxODE5NA==

from table.

eliezer-alves avatar eliezer-alves commented on July 19, 2024 1

//> In 2023, This should work:

This solution worked perfectly for my case, but it is causing me the following typing problem:

Property 'getRowStyles' does not exist on type 'TableMeta'.

I ended up solving this in a very ugly way: I created a custom table type that inherits the Table interface properties from @tanstack/react-table and added the getRowStyles method.

Of course, other errors will arise because this code that I used as an example is not complete and is not all converted to TS.

import { Row, Table } from '@tanstack/react-table';

type CustomTable<TData> = Table<TData> & {
  options?: {
    meta?: {
      getRowStyles?: (row: Row<TData>) => React.CSSProperties;
    };
  };
};

const YourTable = () => {
   const table = useReactTable({
       data,
       columns,
       getCoreRowModel: getCoreRowModel(),
       meta: {
           getRowStyles: (row: Row<YourType>): CSSProperties => ({
               background: row.original.errorStatus === 1 ? "red" : "transparent",
           }),
       }
   }) as CustomTable<any>; <-- Using my custom type

   return (<div><table><tbody>
       {table.getRowModel().rows.map(row => (
           <tr
               key={row.id}
               style={table.options.meta?.getRowStyles(row)}> // <-- Use it here
               {row.getVisibleCells().map(cell => (
                   <td key={cell.id}>
                       {flexRender(cell.column.columnDef.cell, cell.getContext())}
                   </td>
               ))}
           </tr>
       ))}
   </tbody></table></div>);
}

from table.

tannerlinsley avatar tannerlinsley commented on July 19, 2024

I think you're looking for
trClassCallback={ rowInfo => rowInfo.row.status ? 'green' : 'red' }
or
trStyleCallback={ rowInfo => ( {color: rowInfo.row.status ? 'green' : 'red'} ) }

Both of those will help you on your quest! Good luck :)

from table.

sshaginyan avatar sshaginyan commented on July 19, 2024

@tannerlinsley Are trClassCallback & trStyleCallback props for , I've set them and they never get called :-(.

from table.

angkj avatar angkj commented on July 19, 2024

@tannerlinsley Could you give me an example of how to use the getTrProps? I am not sure what is rowInfo or how do i pass it in

EDIT:
I managed to get the rowInfo to work, however, rowInfo.rows does not work for me as no such object exists. I see pageRows attribute, but that does not allow me to get each individual row but the entire data set.

from table.

loukas371 avatar loukas371 commented on July 19, 2024

thanks @aaroncrawford , that if(rowInfo) condition did it for me because I was getting an error previously and I didnt see it in the documentation somewhere.

from table.

mohammedsaket avatar mohammedsaket commented on July 19, 2024

I think you're looking for
trClassCallback={ rowInfo => rowInfo.row.status ? 'green' : 'red' }
or
trStyleCallback={ rowInfo => ( {color: rowInfo.row.status ? 'green' : 'red'} ) }

Both of those will help you on your quest! Good luck :)

Not Working sir..
data={this.state.data}
columns={columns}
defaultPageSize = {15}
pageSizeOptions = {[15,25,100]}
className="-striped -highlight"
trClassCallback={ rowInfo => rowInfo.row.Web_Category ? 'green' : 'red' }

data={this.state.data}
columns={columns}
defaultPageSize = {15}
pageSizeOptions = {[15,25,100]}
className="-striped -highlight"
trStyleCallback={ rowInfo => ( {color: rowInfo.row.status ? 'green' : 'red'} ) }

from table.

AdnanTheExcellent avatar AdnanTheExcellent commented on July 19, 2024

Bumping this. would like to implement highlight a row if someones mouse is hovering over the row. Or if i have a delete button in that row, hovering over the button would create a css affect of that row. Is this currently possible with v7.x?

from table.

wwsskkaa avatar wwsskkaa commented on July 19, 2024

bumping this. also would like to know

from table.

sonali-singh97 avatar sonali-singh97 commented on July 19, 2024

I am able to style a particular row with the help of this: https://jbetancur.github.io/react-data-table-component/?path=/story/conditional-styling--conditional-rows

Example:

const conditionalRowStyles = [
  {
    when: row => row.actual_data!== row.predicted_data,
    style: {
      backgroundColor: 'red'
    }
  }
]

Add conditionalRowStyles as a prop to the Datatable component, and you will achieve the desired style.

from table.

smokinjoe avatar smokinjoe commented on July 19, 2024

Since none of these solutions are applicable for V8, has there been something introduced to replace getTrProps?

from table.

bytesagar avatar bytesagar commented on July 19, 2024

@tannerlinsley as row can we color a individual column too??

from table.

phijma-leukeleu avatar phijma-leukeleu commented on July 19, 2024

//> In 2023, This should work:

This solution worked perfectly for my case, but it is causing me the following typing problem:

Property 'getRowStyles' does not exist on type 'TableMeta'.

I ended up solving this in a very ugly way: I created a custom table type that inherits the Table interface properties from @tanstack/react-table and added the getRowStyles method.

Of course, other errors will arise because this code that I used as an example is not complete and is not all converted to TS.

import { Row, Table } from '@tanstack/react-table';

type CustomTable<TData> = Table<TData> & {
  options?: {
    meta?: {
      getRowStyles?: (row: Row<TData>) => React.CSSProperties;
    };
  };
};

const YourTable = () => {
   const table = useReactTable({
       data,
       columns,
       getCoreRowModel: getCoreRowModel(),
       meta: {
           getRowStyles: (row: Row<YourType>): CSSProperties => ({
               background: row.original.errorStatus === 1 ? "red" : "transparent",
           }),
       }
   }) as CustomTable<any>; <-- Using my custom type

   return (<div><table><tbody>
       {table.getRowModel().rows.map(row => (
           <tr
               key={row.id}
               style={table.options.meta?.getRowStyles(row)}> // <-- Use it here
               {row.getVisibleCells().map(cell => (
                   <td key={cell.id}>
                       {flexRender(cell.column.columnDef.cell, cell.getContext())}
                   </td>
               ))}
           </tr>
       ))}
   </tbody></table></div>);
}

A cleaner way to extend TableMeta is using:

declare module '@tanstack/table-core' {
  interface TableMeta<TData extends unknown> {
    getRowStyles: ...
  }
}

from table.

pedropmedina avatar pedropmedina commented on July 19, 2024

//> In 2023, This should work:
This solution worked perfectly for my case, but it is causing me the following typing problem:
Property 'getRowStyles' does not exist on type 'TableMeta'.
I ended up solving this in a very ugly way: I created a custom table type that inherits the Table interface properties from @tanstack/react-table and added the getRowStyles method.
Of course, other errors will arise because this code that I used as an example is not complete and is not all converted to TS.

import { Row, Table } from '@tanstack/react-table';

type CustomTable<TData> = Table<TData> & {
  options?: {
    meta?: {
      getRowStyles?: (row: Row<TData>) => React.CSSProperties;
    };
  };
};

const YourTable = () => {
   const table = useReactTable({
       data,
       columns,
       getCoreRowModel: getCoreRowModel(),
       meta: {
           getRowStyles: (row: Row<YourType>): CSSProperties => ({
               background: row.original.errorStatus === 1 ? "red" : "transparent",
           }),
       }
   }) as CustomTable<any>; <-- Using my custom type

   return (<div><table><tbody>
       {table.getRowModel().rows.map(row => (
           <tr
               key={row.id}
               style={table.options.meta?.getRowStyles(row)}> // <-- Use it here
               {row.getVisibleCells().map(cell => (
                   <td key={cell.id}>
                       {flexRender(cell.column.columnDef.cell, cell.getContext())}
                   </td>
               ))}
           </tr>
       ))}
   </tbody></table></div>);
}

A cleaner way to extend TableMeta is using:

declare module '@tanstack/table-core' {
  interface TableMeta<TData extends unknown> {
    getRowStyles: ...
  }
}

The issue with declaring meta as show above ^ it's that every table will receive the same types. What if we want to specify meta per table? Is there a way to isolate meta types per table @phijma-leukeleu?

from table.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.