In Storybook, you can update the "args
" provided to a component by using the useArgs
API exported by @storybook/preview-api
(or @storybook/store
in versions of storybook below 7). For example, you can do so using the render
function, like so:
// Storybook 7+
import { useArgs } from '@storybook/preview-api'
import { MyComponent } from './MyComponent'
// ...
export const Default = {
args: {
open: false,
onClick: undefined,
children: 'click me',
},
render: function Render(args) {
// 1: get the component's props/args you want to read current value of
// 2: get the `updateArgs()` function
const [{ open }, updateArgs] = useArgs()
function onClick() {
// 3: update the `open` prop to a new value using `updateArgs()`
updateArgs({ open: !open })
}
// 4: pass original `args` and updated props to the component (order matters)
return (
<MyComponent { ...args } onClick={onClick} />
)
},
}
In this example, the value of "open
" is changed to the opposite of its current value, and newer versions of "open
" and "onClick
" are passed to "MyComponent
", reflecting the changes in the UI as you interact with the component in storybook.
If you do not wish to make use of any existing values from the "args
" object, then you may destructure the useArgs()
hook with a leading comma to only get the updateArgs
function, for example, like so:
// ...
const [, updateArgs] = useArgs()
// ...
To demonstrate this, consider the following example:
// Storybook 7+
import { useArgs } from '@storybook/preview-api'
import { MyComponent } from './MyComponent'
// ...
export const Default = {
args: {
open: true,
onClick: undefined,
children: 'click me',
},
render: function Render(args) {
const [, updateArgs] = useArgs()
function closeMenu() {
updateArgs({ open: false })
}
return (
<MyComponent { ...args } onClick={closeMenu} />
)
},
}
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.