Skip to content

Commit

Permalink
Merge pull request #1142 from nsbno/fix-radio-cards
Browse files Browse the repository at this point in the history
Buypass any element that is not RadioCard in RadioCardGroup
  • Loading branch information
alicemacl authored May 14, 2024
2 parents 9e2eb59 + b8a8ce5 commit b097dff
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 7 deletions.
5 changes: 5 additions & 0 deletions .changeset/heavy-horses-sparkle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@vygruppen/spor-react": patch
---

Fix render of RadioCardGroup and RadioCard
2 changes: 1 addition & 1 deletion packages/spor-react/src/layout/RadioCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
import { dataAttr } from "@chakra-ui/utils";
import React, { useId } from "react";

type RadioCardProps = UseRadioProps &
export type RadioCardProps = UseRadioProps &
BoxProps & {
children: React.ReactNode;
/** Defaults to "base" */
Expand Down
38 changes: 32 additions & 6 deletions packages/spor-react/src/layout/RadioCardGroup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
Stack,
} from "@chakra-ui/react";
import React, { Children } from "react";
import { RadioCard, RadioCardProps } from "./RadioCard";

type RadioCardGroupProps = RadioGroupProps & {
children: React.ReactNode;
Expand Down Expand Up @@ -78,13 +79,38 @@ export const RadioCardGroup = ({

return (
<Stack direction={direction} {...group}>
{Children.map(
children as React.ReactElement[],
(child: React.ReactElement) => {
{recursiveMap(children, (child: React.ReactElement) => {
if (child.type === RadioCard) {
const radio = getRadioProps({ value: child.props.value });
return React.cloneElement(child, { ...radio, variant, ...props });
},
)}
const variantValue = variant as "base" | "floating" | undefined;
return React.cloneElement(
child as React.ReactElement<RadioCardProps>,
{ ...radio, variant: variantValue, ...props },
);
}
return child;
})}
</Stack>
);
};

function recursiveMap(
children: React.ReactNode,
fn: (child: React.ReactElement) => React.ReactElement,
): React.ReactNode {
return React.Children.map(children, (child) => {
// If this child is a React element and has children, recurse
if (React.isValidElement(child) && child.props.children) {
child = React.cloneElement(child as React.ReactElement<any>, {
children: recursiveMap(child.props.children, fn),
});
}

// Apply the function to the child (if it's a React element)
if (React.isValidElement(child)) {
return fn(child);
}

return child;
});
}

0 comments on commit b097dff

Please sign in to comment.