Is it necessary to have {} inside Template.bind({}) while making stories in Storybook

6.2k views Asked by At

Recently I have started learning to react Storybook. In the below example, when I don't write {} in Template.bind({}), the Storybook will run absolutely fine without any error. But I have found that many of the people use {} in Template.bind({}) while making stories.

Question: Is it necessary to have {} inside Template.bind({}) while making stories in Storybook?

import React from 'react'
import { MyButton } from './MyButton'

export default {
    title :  'MyButton',
    component : MyButton
};

const Template = (args) => <MyButton {...args}/>

export const Primary = Template.bind()
Primary.args = {
    variant: 'primary',
    label: 'button'
}
2

There are 2 answers

3
daGo On

Template.bind({}) is a waste of time/resources since it creates an object on every invocation, so basically yeah - Template.bind() will suffice. If no arguments are provided to bind nothing bad will happen.

0
ChrisCrossCrash On

No, {} is not necessary or important.

.bind(thisArg) is a method that you can call on a function to return a new function with its this keyword set to whatever you pass to thisArg. However, on an arrow function (like in your example), it doesn't matter what you pass as thisArg, since this works differently on arrow functions. Calling .bind() will just return a new clone of the function.

The .bind() method is only being used here to clone the Template() function. The binding behavior isn't really important (especially because it's an arrow function). The important part is that when you do this:

export const Primary = Template.bind()
Primary.args = {
    variant: 'primary',
    label: 'button'
}

Primary gets its own args property. You get multiple clones of the Template function that don't interfere with each other.

Here's an answer to a different question, which explains how to clone a function with its .bind() method in more detail.