Skip to content

Commit 7433ebf

Browse files
authored
fix(tilegroup): guard usage of potentially null children properties (#17258)
1 parent d34a20c commit 7433ebf

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

packages/react/src/components/TileGroup/TileGroup.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ const TileGroup = (props) => {
9191
const traverseAndModifyChildren = (children) => {
9292
return React.Children.map(children, (child) => {
9393
// If RadioTile found, return it with necessary props
94-
if (child.type === RadioTile) {
94+
if (child?.type === RadioTile) {
9595
const { value, ...otherProps } = child.props;
9696
return (
9797
<RadioTile
@@ -104,7 +104,7 @@ const TileGroup = (props) => {
104104
checked={value === selected}
105105
/>
106106
);
107-
} else if (child.props && child.props.children) {
107+
} else if (child?.props?.children) {
108108
// If the child is not RadioTile and has children, recheck the children
109109
return React.cloneElement(child, {
110110
...child.props,

packages/react/src/components/TileGroup/__tests__/TileGroup-test.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import React from 'react';
99
import TileGroup from '../TileGroup';
1010
import RadioTile from '../../RadioTile/RadioTile';
11+
import Button from '../../Button';
1112
import userEvent from '@testing-library/user-event';
1213
import { render, screen } from '@testing-library/react';
1314
import { FeatureFlags } from '../../FeatureFlags';
@@ -94,6 +95,39 @@ describe('TileGroup', () => {
9495
expect(screen.getByDisplayValue('test-2')).toBeRequired();
9596
});
9697

98+
it('should handle non-RadioTile (null) children', async () => {
99+
const ToggleableRadioTiles = () => {
100+
const [showSecondTile, setShowSecondTile] = React.useState(true);
101+
return (
102+
<>
103+
<Button onClick={() => setShowSecondTile(!showSecondTile)}>
104+
Toggle second tile
105+
</Button>
106+
107+
<TileGroup defaultSelected="test-1" legend="TestGroup" name="test">
108+
<RadioTile id="test-1" value="test-1">
109+
Option 1
110+
</RadioTile>
111+
{showSecondTile && (
112+
<RadioTile id="test-2" value="test-2">
113+
Option 2
114+
</RadioTile>
115+
)}
116+
</TileGroup>
117+
</>
118+
);
119+
};
120+
render(<ToggleableRadioTiles />);
121+
122+
expect(screen.getByDisplayValue('test-1')).toBeVisible();
123+
expect(screen.getByDisplayValue('test-2')).toBeVisible();
124+
125+
await userEvent.click(screen.getByRole('button'));
126+
127+
expect(screen.getByDisplayValue('test-1')).toBeVisible();
128+
expect(screen.queryByDisplayValue('test-2')).not.toBeInTheDocument();
129+
});
130+
97131
it('should support a custom `className` on the outermost element', () => {
98132
const { container } = render(
99133
<TileGroup

0 commit comments

Comments
 (0)