Last active
September 13, 2024 05:15
-
-
Save shumbo/3bbb8a2dea5ea0a90ecf0b7c103783e8 to your computer and use it in GitHub Desktop.
A storybook decorator to use React Hooks Form inside stories
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default { | |
title: "MyComponent", | |
component: MyComponent, | |
decorators: [withRHF(false)], // or true to show submit button on story | |
} as Meta; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { action } from "@storybook/addon-actions"; | |
import { StoryFnReactReturnType } from "@storybook/react/dist/client/preview/types"; | |
import { VFC, ReactNode, FC } from "react"; | |
import { FormProvider, useForm } from "react-hook-form"; | |
const StorybookFormProvider: VFC<{ children: ReactNode }> = ({ children }) => { | |
const methods = useForm(); | |
return ( | |
<FormProvider {...methods}> | |
<form | |
onSubmit={methods.handleSubmit(action("[React Hooks Form] Submit"))} | |
> | |
{children} | |
</form> | |
</FormProvider> | |
); | |
}; | |
export const withRHF = (showSubmitButton: boolean) => ( | |
Story: FC | |
): StoryFnReactReturnType => ( | |
<StorybookFormProvider> | |
<Story /> | |
{showSubmitButton && <button type="submit">Submit</button>} | |
</StorybookFormProvider> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How do that in sb8 or sb9?