📖 Storybook with simple 🍦vanilla webcomponents

ioroot

The Administrator

Posted on June 12, 2023

📖 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.

💖 💪 🙅 🚩
ioroot
The Administrator

Posted on June 12, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related