Skip to content

Commit

Permalink
feat: add onToggle prop to DisplayIf
Browse files Browse the repository at this point in the history
  • Loading branch information
Pagebakers committed Nov 23, 2023
1 parent 91412d7 commit 6899555
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/odd-buttons-stare.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@saas-ui/forms': minor
---

Added new onToggle prop to DisplayIf
6 changes: 5 additions & 1 deletion apps/website/src/pages/docs/components/forms/form/usage.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,11 @@ export default function ConditionalFields() {
label="Ship to my home address"
/>

<DisplayIf name="ship" condition={(ship) => !!ship}>
<DisplayIf
name="ship"
condition={(ship) => !!ship}
onToggle={(matches) => console.log(matches)}
>
<FormLayout>
<Heading size="md" mt="4">
Address
Expand Down
23 changes: 22 additions & 1 deletion packages/saas-ui-forms/src/display-if.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ export interface DisplayIfProps<
isDisabled?: boolean
isExact?: boolean
condition?: (value: unknown, context: UseFormReturn<TFieldValues>) => boolean
onToggle?: (
conditionMatched: boolean,
context: UseFormReturn<TFieldValues>
) => void
}
/**
* Conditionally render parts of a form.
Expand All @@ -34,15 +38,32 @@ export const DisplayIf = <
isDisabled,
isExact,
condition = (value) => !!value,
onToggle,
}: DisplayIfProps<TFieldValues, TName>) => {
const initializedRef = React.useRef(false)
const matchesRef = React.useRef(false)

const value = useWatch<TFieldValues>({
name,
defaultValue: defaultValue as any,
disabled: isDisabled,
exact: isExact,
})
const context = useFormContext() as any
return condition(value, context) ? children : null

const matches = condition(value, context)

React.useEffect(() => {
if (!initializedRef.current) {
initializedRef.current = true
return
}
if (matchesRef.current === matches) return
matchesRef.current = matches
onToggle?.(matches, context)
}, [value])

return matches ? children : null
}

DisplayIf.displayName = 'DisplayIf'

1 comment on commit 6899555

@vercel
Copy link

@vercel vercel bot commented on 6899555 Nov 23, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.