Skip to content

Instantly share code, notes, and snippets.

@natac13
Forked from shumbo/story.tsx
Created October 6, 2022 12:23
Show Gist options
  • Save natac13/fbf08b3337ebd0e342592aac835edb99 to your computer and use it in GitHub Desktop.
Save natac13/fbf08b3337ebd0e342592aac835edb99 to your computer and use it in GitHub Desktop.
A storybook decorator to use React Hooks Form inside stories
export default {
title: "MyComponent",
component: MyComponent,
decorators: [withRHF(false)], // or true to show submit button on story
} as Meta;
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