I have a toggler button in each tr of my ant design table that when the user clicks on it, I want to add/remove a specific class to/from its parent tr.
I know there are ways with vanilla js but I'm coding with React library, so I don't want to manipulate DOM directly.
To be more precise, I already tried rowClassName
and it won't help! (It adds the given class to all of the rows.)
Check the following example, index.css file has CSS which changes the background color of the row depending on the Switch
value, and removes the default hover effect of antd
index.css
.row-light {
background-color: #b6c5f5;
}
.row-dark {
background-color: #84eb84;
}
.ant-table-thead>tr.ant-table-row-hover:not(.ant-table-expanded-row)>td,
.ant-table-tbody>tr.ant-table-row-hover:not(.ant-table-expanded-row)>td,
.ant-table-thead>tr:hover:not(.ant-table-expanded-row)>td,
.ant-table-tbody>tr:hover:not(.ant-table-expanded-row)>td {
background: unset;
}
Following is react code, it uses rowClassName
property of antd table to change the css class of rows.
Demo.js
import React from 'react';
import 'antd/dist/antd.css';
import './index.css';
import { Table, Switch } from 'antd';
import { useState } from 'react';
const Demo = () => {
const [users, setUsers] = useState([
{
key: '1',
name: 'John Brown',
age: 32,
toggle: true,
},
{
key: '2',
name: 'Jim Green',
age: 42,
toggle: false,
},
{
key: '3',
name: 'Joe Black',
age: 32,
toggle: false,
},
{
key: '4',
name: 'Peter Black',
age: 72,
toggle: true,
},
]);
const columns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
},
{
title: 'Age',
dataIndex: 'age',
key: 'age',
},
{
title: 'Action',
key: 'toggle',
render: (text, record) => (
<Switch
size="small"
onChange={(value) => onSwitchChange(record, value)}
checked={record.toggle}
/>
),
},
];
/* Updates the toggle property(true or false) of selected user */
const onSwitchChange = (record, value) => {
let key = record.key;
let data = users.map((user) => {
if (user.key === record.key)
return { ...user, toggle: value };
else return user;
});
setUsers(data);
console.log(users);
};
return (
<Table
rowClassName={(record, index) =>
record.toggle === true ? 'row-light' : 'row-dark'
}
columns={columns}
dataSource={users}
/>
);
};
export default Demo