button-group.tsx 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { Children, ReactElement, cloneElement } from 'react';
  2. import { ButtonProps } from '@/components/ui/button';
  3. import { cn } from '@/lib/utils';
  4. interface ButtonGroupProps {
  5. className?: string;
  6. orientation?: 'horizontal' | 'vertical';
  7. children: ReactElement<ButtonProps>[];
  8. }
  9. export const ButtonGroup = ({
  10. className,
  11. orientation = 'horizontal',
  12. children,
  13. }: ButtonGroupProps) => {
  14. const totalButtons = Children.count(children);
  15. const isHorizontal = orientation === 'horizontal';
  16. const isVertical = orientation === 'vertical';
  17. return (
  18. <div
  19. className={cn(
  20. 'flex',
  21. {
  22. 'flex-col': isVertical,
  23. 'w-fit': isVertical,
  24. },
  25. className
  26. )}
  27. >
  28. {Children.map(children, (child, index) => {
  29. const isFirst = index === 0;
  30. const isLast = index === totalButtons - 1;
  31. return cloneElement(child, {
  32. className: cn(
  33. {
  34. 'rounded-l-none': isHorizontal && !isFirst,
  35. 'rounded-r-none': isHorizontal && !isLast,
  36. 'border-l-0': isHorizontal && !isFirst,
  37. 'rounded-t-none': isVertical && !isFirst,
  38. 'rounded-b-none': isVertical && !isLast,
  39. 'border-t-0': isVertical && !isFirst,
  40. },
  41. child.props.className
  42. ),
  43. });
  44. })}
  45. </div>
  46. );
  47. };