Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading