Skip to content

Commit e1110ef

Browse files
committed
fix: DefinitionListの子要素処理ロジックを改善
1 parent 1b9186e commit e1110ef

File tree

1 file changed

+34
-15
lines changed

1 file changed

+34
-15
lines changed

packages/smarthr-ui/src/components/DefinitionList/DefinitionList.tsx

Lines changed: 34 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
Fragment,
66
type PropsWithChildren,
77
type ReactElement,
8+
type ReactNode,
89
cloneElement,
910
isValidElement,
1011
useMemo,
@@ -36,6 +37,38 @@ const classNameGenerator = tv({
3637
base: 'smarthr-ui-DefinitionList shr-my-[initial]',
3738
})
3839

40+
// children のうち DefinitionListItem にだけ maxColumns / termStyleType を注入して返す
41+
function childrenToItems(
42+
children: ReactNode,
43+
extra: Pick<ItemType, 'maxColumns' | 'termStyleType'>,
44+
): ReactNode[] {
45+
const out: ReactNode[] = []
46+
47+
const walk = (nodes: ReactNode) => {
48+
Children.forEach(nodes, (child) => {
49+
if (!isValidElement(child)) {
50+
out.push(child)
51+
return
52+
}
53+
54+
if (child.type === Fragment) {
55+
walk(child.props.children) // Fragment は再帰的に展開
56+
return
57+
}
58+
59+
// DefinitionListItem にだけ追加 props を注入
60+
if (child.type === DefinitionListItem) {
61+
out.push(cloneElement(child, extra))
62+
} else {
63+
out.push(child) // 他の要素はそのまま
64+
}
65+
})
66+
}
67+
68+
walk(children)
69+
return out
70+
}
71+
3972
export const DefinitionList: FC<Props & ElementProps> = ({
4073
items,
4174
maxColumns,
@@ -56,21 +89,7 @@ export const DefinitionList: FC<Props & ElementProps> = ({
5689
termStyleType={termStyleType}
5790
/>
5891
))}
59-
{Children.toArray(children)
60-
.flatMap((child) => {
61-
if (isValidElement(child) && child.type === Fragment) {
62-
return Children.toArray(child.props.children)
63-
}
64-
return child
65-
})
66-
.map((child) =>
67-
isValidElement(child)
68-
? cloneElement(child as ReactElement, {
69-
maxColumns,
70-
termStyleType,
71-
})
72-
: child,
73-
)}
92+
{childrenToItems(children, { maxColumns, termStyleType })}
7493
</Cluster>
7594
)
7695
}

0 commit comments

Comments
 (0)