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' ;
33import { twMerge } from 'tailwind-merge' ;
44import { mergeDeep } from '../../helpers/merge-deep' ;
55import { 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+
2556export 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