Skip to content

Instantly share code, notes, and snippets.

@shumbo
Last active April 15, 2024 05:07
Show Gist options
  • Save shumbo/3bbb8a2dea5ea0a90ecf0b7c103783e8 to your computer and use it in GitHub Desktop.
Save shumbo/3bbb8a2dea5ea0a90ecf0b7c103783e8 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>
);
@bogris
Copy link

bogris commented Feb 27, 2024

just what we needed now!

Bravo!

@koorya
Copy link

koorya commented Mar 16, 2024

How do that in sb8 or sb9?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment