Home > other >  React table changing style of cell onClick
React table changing style of cell onClick

Time:02-17

I'm new to react table, I've created the basic table using react-table. I'm not able to figure out how to change the color of a cell when click on that particular cell. I don't find any resource or related question on Stackoverflow.

Here is my Code looks like:

import React, { useMemo } from 'react'
import { useTable } from 'react-table'
import MOCK_DATA from '../MOCK_DATA.json'
import { COLUMN } from './Column'
import './table.css'

export const BasicTable = () => {
  const columns = useMemo(() => COLUMN, [])
  const data = useMemo(() => MOCK_DATA, [])

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    footerGroups,
    rows,
    prepareRow
  } = useTable({
    columns,
    data
  })

  return (
    <>
      <table {...getTableProps()}>
        <thead>
          {headerGroups.map(headerGroup => (
            <tr {...headerGroup.getHeaderGroupProps()}>
              {headerGroup.headers.map(column => (
                <th {...column.getHeaderProps()}>{column.render('Header')}</th>
              ))}
            </tr>
          ))}
        </thead>
        <tbody {...getTableBodyProps()}>
          {rows.map(row => {
            prepareRow(row)
            return (
              <tr {...row.getRowProps()}>
                {row.cells.map(cell => {
                  return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
                })}
              </tr>
            )
          })}
        </tbody>
        <tfoot>
          {footerGroups.map(footerGroup => (
            <tr {...footerGroup.getFooterGroupProps()}>
              {footerGroup.headers.map(column => (
                <td {...column.getFooterProps()}>{column.render('Footer')}</td>
              ))}
            </tr>
          ))}
        </tfoot>
      </table>
    </>
  )
}

I'm getting demo data in MOCK_DATA(it's just random data). When I click on particular cell I want that particular cell color change. How I should approach this. In react if we want to change color of button or anything else we can use useState to do that but I'm not able to figure out here.

Here is the live example: https://codesandbox.io/s/focused-field-2sgkqz?file=/src/MOCK_DATA.json:35842-48670

CodePudding user response:

you want is:when you click a particular cell,that particular cell change color? if so, you just need remember the selected row.like is demo, is this you want ?

  • Related