How to insert JSX in Storybook control
Asked Answered
A

2

14

Running Storybook I'd like to navigate to my component and play with Docs tab and check its behavior as I change control value for each property. I implemented a component Footer that could receive string | JSX.Element | React.FunctionComponent types (I'm using TypeScript along ReactJS).

Unfortunately, when I type <div>my jsx</div> inside control field, a red border comes up pointing error and doesn't update the component in the preview as expected.

This is the screen I'm trying to insert into control field: enter image description here

In the .stories.js file I have at the end:

export const Default = Template.bind({});
Default.args = {
    subscribe: "Replace me by the Subscribe component of Design System.",
    brand: <figure>Put branding logo here!</figure>,
    links: <div><div>first column of links</div><div>second column of links</div></div>,
    bottom: "All rights reserved."
}

The Links text is the default value for link property (from the actual React component file). As the code and image above can show us, it seems the JSX argument passed on Default.args in .stories.js file is completely ignored.

I'd like to insert a JSX into control field of storybook playground and then get Footer component live updated with JSX component rendered in the preview. How can I achieve that?

Airel answered 17/3, 2022 at 21:53 Comment(1)
As of right now there is no way to do this. However you can look into mapping for complex arg types which may be a good middle ground.Recreation
P
7

I hope you find the answer till now, But I personally use the following config which is the items in a navbar:

const NavLink = () => (
  <div style={{ display: 'flex', gap: '16px', fontSize: '16px' }}>
    <a href="#">Home</a>
    <a href="#">Portfolio</a>
    <a href="#">About</a>
    <a href="#">Contact</a>
  </div>
);

export default {
  title: 'common/Navbar',
  component: Navbar,
  argTypes: {
    children: {
      control: {
        type: 'select',
        options: ['empty', 'links'],
      },
      mapping: {
        empty: [],
        links: <NavLink />,
      },
    },
  },
} as ComponentMeta<typeof Navbar>;

It works for me!

Piecework answered 17/3, 2023 at 7:45 Comment(1)
I should try it in the project before vote in your answer and as the company I'm working for owns the project, and it's temporary paused, I need permission to make changes on it. As soon the project returns to activity I'll test it. Thank you any way!Tumble
E
1

Some extra information here: https://github.com/storybookjs/storybook/blob/next/docs/writing-stories/args.md#mapping-to-complex-arg-values

FYI, it works with booleans:

leftIcon: {
  control: { type: 'boolean' },
  mapping: { false: '', true: <PlusIcon /> },
},
Edmiston answered 5/6, 2023 at 3:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.