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' ;
3
3
import { twMerge } from 'tailwind-merge' ;
4
4
import { mergeDeep } from '../../helpers/merge-deep' ;
5
5
import { getTheme } from '../../theme-store' ;
@@ -22,6 +22,37 @@ export interface ButtonGroupProps extends ComponentProps<'div'>, Pick<ButtonProp
22
22
theme ?: DeepPartial < FlowbiteButtonGroupTheme > ;
23
23
}
24
24
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
+
25
56
export const ButtonGroup : FC < ButtonGroupProps > = ( {
26
57
children,
27
58
className,
@@ -30,18 +61,8 @@ export const ButtonGroup: FC<ButtonGroupProps> = ({
30
61
theme : customTheme = { } ,
31
62
...props
32
63
} : 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
+
45
66
const theme = mergeDeep ( getTheme ( ) . buttonGroup , customTheme ) ;
46
67
47
68
return (
0 commit comments