Skip to content

Commit d0dc810

Browse files
authored
fix(ButtonGroup): dynamic generated button with group wasn't styled properly (#1273)
fix(/button/buttongroup.tsx): dynamic generated buton with group wasnt styled properly Dynamically generated buttons within a button group are not properly styled. #1269 fix #1269
1 parent 2c2fa52 commit d0dc810

File tree

1 file changed

+35
-14
lines changed

1 file changed

+35
-14
lines changed

src/components/Button/ButtonGroup.tsx

+35-14
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import type { ComponentProps, FC, ReactElement } from 'react';
2-
import { Children, cloneElement, useMemo } from 'react';
1+
import type { ComponentProps, FC, ReactElement, ReactNode } from 'react';
2+
import { Children, cloneElement, isValidElement, useMemo } from 'react';
33
import { twMerge } from 'tailwind-merge';
44
import { mergeDeep } from '../../helpers/merge-deep';
55
import { getTheme } from '../../theme-store';
@@ -22,6 +22,37 @@ export interface ButtonGroupProps extends ComponentProps<'div'>, Pick<ButtonProp
2222
theme?: DeepPartial<FlowbiteButtonGroupTheme>;
2323
}
2424

25+
const processChildren = (
26+
children: React.ReactNode,
27+
outline: boolean | undefined,
28+
pill: boolean | undefined,
29+
): ReactNode => {
30+
return Children.map(children as ReactElement<ButtonProps>[], (child, index) => {
31+
if (isValidElement(child)) {
32+
// Check if the child has nested children
33+
if (child.props.children) {
34+
// Recursively process nested children
35+
return cloneElement(child, {
36+
...child.props,
37+
children: processChildren(child.props.children, outline, pill),
38+
positionInGroup: determinePosition(index, Children.count(children)),
39+
});
40+
} else {
41+
return cloneElement(child, {
42+
outline,
43+
pill,
44+
positionInGroup: determinePosition(index, Children.count(children)),
45+
});
46+
}
47+
}
48+
return child;
49+
});
50+
};
51+
52+
const determinePosition = (index: number, totalChildren: number) => {
53+
return index === 0 ? 'start' : index === totalChildren - 1 ? 'end' : 'middle';
54+
};
55+
2556
export const ButtonGroup: FC<ButtonGroupProps> = ({
2657
children,
2758
className,
@@ -30,18 +61,8 @@ export const ButtonGroup: FC<ButtonGroupProps> = ({
3061
theme: customTheme = {},
3162
...props
3263
}: ButtonGroupProps) => {
33-
const items = useMemo(
34-
() =>
35-
Children.map(children as ReactElement<ButtonProps>[], (child, index) =>
36-
cloneElement(child, {
37-
outline,
38-
pill,
39-
positionInGroup:
40-
index === 0 ? 'start' : index === (children as ReactElement<ButtonProps>[]).length - 1 ? 'end' : 'middle',
41-
}),
42-
),
43-
[children, outline, pill],
44-
);
64+
const items = useMemo(() => processChildren(children, outline, pill), [children, outline, pill]);
65+
4566
const theme = mergeDeep(getTheme().buttonGroup, customTheme);
4667

4768
return (

0 commit comments

Comments
 (0)