Using Storybook with Radix UI

Viewed 14

I'm using Radix UI to build out my components (basically just styling their primitives and exporting them together). For example, I have this in my Checkbox.tsx file:

import { CheckIcon as StyledCheckIcon } from '@radix-ui/react-icons'
import * as CheckboxPrimitive from '@radix-ui/react-checkbox'
import { styled } from '@stitches/react'

const StyledContainer = styled('div', {
    ...
})

const StyledCheckbox = styled(CheckboxPrimitive.Root, {
    ...
})

const StyledIndicator = styled(CheckboxPrimitive.Indicator, {
    ...
})

const StyledLabel = styled('label', {
    ...
})

export const Container = StyledContainer
export const Root = StyledCheckbox
export const Indicator = StyledIndicator
export const CheckIcon = StyledCheckIcon
export const Label = StyledLabel

I can use this in App.tsx in the following way:

import * as Checkbox from "./components/Checkbox";

function App() {
  return (
    <Checkbox.Container>
      <Checkbox.Root id="c1" defaultChecked>
        <Checkbox.Indicator>
          <Checkbox.CheckIcon />
        </Checkbox.Indicator>
      </Checkbox.Root>
      <Checkbox.Label htmlFor="c1">
        Accept terms and conditions
      </Checkbox.Label>
    </Checkbox.Container>
  )
}

This works perfectly fine, however, when I want to actually create a story for this component, it gets a bit difficult (mainly because it's not really just a component, it's a composite). I can do the following in my Checkbox.stories.tsx:

import React from 'react';
import { ComponentStory, ComponentMeta } from '@storybook/react';
import * as Checkbox from '../components/Checkbox';

const CheckboxComponent:any = function() {
  return (
    <Checkbox.Container>
      <Checkbox.Root id="c1" defaultChecked>
        <Checkbox.Indicator>
          <Checkbox.CheckIcon />
        </Checkbox.Indicator>
      </Checkbox.Root>
      <Checkbox.Label htmlFor="c1">
        Accept terms and conditions
      </Checkbox.Label>
    </Checkbox.Container>
  )
}

export default {
  title: 'Example/Checkbox',
  component: CheckboxComponent,
} as ComponentMeta<typeof CheckboxComponent>;

const Template: ComponentStory<typeof CheckboxComponent> = (args) => <CheckboxComponent {...args} />;

export const Default = Template.bind({});

This runs okay and the output is a checkbox, but I can't automatically control the props on the Root and the Indicator which are styled Radix primitives: Checkbox docs from Radix. How do I use Storybook with Radix components?

0 Answers
Related