Storybook: callback when a story has been rendered

3.9k views Asked by At

I'm working with Storybook for components creation in pure HTML, CSS and JS (jQuery actually).

I'm wondering if there's a callback function when a story is rendered on the screen (like useEffect for React) because I need to run then the relative jQuery code only when the component is really in the DOM.

Here's my situation:

// Button.stories.js

// my pure HTML component
const Button = () => `<button>My button </button>`;


export default {
    title: 'Buttons',
};

export const ButtonStory = () => Button()

// would be great something like: ButtonStory.callback = function(){ do this}

There's something without workaround? (Like wrap the HTML component inside react component and use useEffect for trigger the code)

Thanks

1

There are 1 answers

3
Pierfrancesco On BEST ANSWER

I'll share a not optimal solution I've found but maybe could be useful for others:

MyStory.stories.js

import {ActionBar} from '../public/components/ActionBar/actionbar.module';
import controller from "!raw-loader!../public/components/ActionBar/controller.js";
import customRenderStory from "../utils/customRenderStory";

export default {
    title: 'Basic/ActionBar',
};

//
export const ActionBarToExport= () =>
    customRenderStory(
        ActionBar(),
        controller,
        2000
    );

customRenderStory.js

export default (component, javascript, timeout) => {
    if (javascript !== undefined) setTimeout(() => eval(javascript), timeout)
    return component;
}

In this way, I can execute the code inside controller.js each time the story is rendered. I need a timeout (which can be configured) because I can't be sure that the component will be mounted after the code execution.

In my case, StoryBook in plain HTML and jQuery, seems is working.