8

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'
}
DevLoverUmar
  • 11,809
  • 11
  • 68
  • 98

2 Answers2

8

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.

ChrisCrossCrash
  • 651
  • 8
  • 18
1

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.

daGo
  • 2,584
  • 26
  • 24
  • Then why when I remove the `{}` it shows an error saying: `Expected at least 1 arguments, but got 0.` – Diego Ortiz Sep 15 '21 at 21:17
  • 1
    `function f(){} f.bind()` I don't see any errors – daGo Sep 17 '21 at 07:37
  • I get the same `Expected at least 1 arguments, but got 0.ts(2555) lib.es5.d.ts(353, 22): An argument for 'thisArg' was not provided.`, but `null` or `undefined` can be used to work around it without creating new objects. – Qwerty May 21 '23 at 20:28