DEV Community

Cover image for 📖 Storybook with simple 🍦vanilla webcomponents
The Administrator
The Administrator

Posted on

📖 Storybook with simple 🍦vanilla webcomponents

It took me way too long to figure out how to get simple custom vanilla javascript webcomponents working in storybook.
The documentation has no examples and I couldn't find much info online, so thought I'd share how to do it in 4 easy steps. (more for me to have a record to remember how to do it)

1 - Install storybook for HTML only. (this info is hidden behind an accordion on the install page)

npx storybook@latest init --type html 
Enter fullscreen mode Exit fullscreen mode

2 - Start storybook up.

npm run storybook
Enter fullscreen mode Exit fullscreen mode

3 - Create your webcomponent file in ./stories/my-component.js

// Define your web component
class MyWebComponent extends HTMLElement {
    connectedCallback() {
      this.innerHTML = '<p>This is my web component</p>';
    }
  }

  // Register your web component
  customElements.define('my-web-component', MyWebComponent);
Enter fullscreen mode Exit fullscreen mode

4 - Create your story file in ./stories/my-component.stories.js

import './my-component.js';

export default {
  title: 'Example/My-Component'
};

export const Default = () => {
  return document.createElement('my-web-component');
};
Enter fullscreen mode Exit fullscreen mode

That's it.

Storybook should now render your vanilla webcomponent. Sorry if this is super-basic, but hopefully it'll help others getting started with storybook without any extra frameworks.

Top comments (0)