Skip to content

Commit

Permalink
feat: forwardref added in tablecell (#17760)
Browse files Browse the repository at this point in the history
* feat: forwardref added in tablecell

* feat: forwardref added in tablecell

* feat: add unit test for ref in tablecell
  • Loading branch information
anamikaanu96 authored Oct 17, 2024
1 parent 1232b5e commit e840ffd
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 23 deletions.
6 changes: 4 additions & 2 deletions packages/react/__tests__/__snapshots__/PublicAPI-test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -2000,7 +2000,8 @@ Map {
},
},
"TableCell": Object {
"displayName": "TableCell",
"$$typeof": Symbol(react.forward_ref),
"render": [Function],
},
"TableContainer": Object {
"propTypes": Object {
Expand Down Expand Up @@ -8016,7 +8017,8 @@ Map {
},
},
"TableCell" => Object {
"displayName": "TableCell",
"$$typeof": Symbol(react.forward_ref),
"render": [Function],
},
"TableContainer" => Object {
"propTypes": Object {
Expand Down
39 changes: 18 additions & 21 deletions packages/react/src/components/DataTable/TableCell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,27 +37,24 @@ interface TableCellProps extends ReactAttr<HTMLTableCellElement> {
headers?: string;
}

const TableCell = ({
children,
className,
hasSlugHeader,
colSpan,
...rest
}: TableCellProps) => {
const prefix = usePrefix();

const tableCellClassNames = classNames(className, {
[`${prefix}--table-cell--column-slug`]: hasSlugHeader,
});
return (
<td
className={tableCellClassNames ? tableCellClassNames : undefined}
colSpan={colSpan}
{...rest}>
{children}
</td>
);
};
const TableCell = React.forwardRef<HTMLTableCellElement, TableCellProps>(
({ children, className, hasSlugHeader, colSpan, ...rest }, ref) => {
const prefix = usePrefix();

const tableCellClassNames = classNames(className, {
[`${prefix}--table-cell--column-slug`]: hasSlugHeader,
});
return (
<td
className={tableCellClassNames ? tableCellClassNames : undefined}
ref={ref}
colSpan={colSpan}
{...rest}>
{children}
</td>
);
}
);

TableCell.displayName = 'TableCell';
export default TableCell;
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,24 @@ describe('TableCell', () => {
'test'
);
});

it('should forward refs to the rendered cell element', () => {
let td = null;
const ref = jest.fn((node) => {
td = node;
});
const { container } = render(
<Table>
<TableBody>
<TableRow data-testid="tr">
<TableCell ref={ref} className="custom-class" />
</TableRow>
</TableBody>
</Table>
);
expect(ref).toHaveBeenCalled();
expect(td).not.toBeNull();
expect(td).toEqual(container.querySelector('td'));
expect(td).toHaveClass('custom-class');
});
});

0 comments on commit e840ffd

Please sign in to comment.