-
-
Save natac13/fbf08b3337ebd0e342592aac835edb99 to your computer and use it in GitHub Desktop.
A storybook decorator to use React Hooks Form inside stories
This file contains hidden or 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 hidden or 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