How can I highlight one row in antd table with useState?

Advertisements

So I have a table with coordinates, and when I click on one particular row it should be highlighted and other rows should be default color.
For now it looks like this:

const TableComponent = () => {
  const [active, setActive] = useState(false);

  useEffect(() => {
    console.log(active);
  }, [active]);

  return (
    <Table
      dataSource={dataSource}
      columns={columns}
      rowClassName={active ? "green" : null}
      onRow={(record, rowIndex) => {
        return {
          onClick: (event) => {
            setActive(true);
          }, // click row
        };
      }}
    />
  );
};

export default TableComponent;

When I click on one row all of the rows get highlighted, how could I make it only to one row?

>Solution :

You can set the active record, and compare it with the record argument of the rowClassName prop function. If they are the same, then set your custom class name to this row you clicked.

rowClassName prop has function(record, index): string signature, you should always return a string instead of null.

type ID = string | number;

const TableComponent = () => {
  const [activeRecord, setActiveRecord] = useState<{ id: ID }>();

  console.log(activeRecord);

  return (
    <Table
      dataSource={dataSource}
      columns={columns}
      rowClassName={(record) =>  record.id === activeRecord?.id ? "green" : ''}
      onRow={(record) => {
        return {
          onClick: () => {
            setActiveRecord(record);
          }, 
        };
      }}
    />
  );
};

export default TableComponent;

antd version: v5.0.5

Leave a ReplyCancel reply