How to update arg in storybook with a function?

36 Views Asked by At

I am using a storybook version 8. I have a select component that takes in two arguments: number and function. Function is being called on select change event and should change number argument to a new selected value. How can I do this?

This is storybook story:

const meta = {
  title: 'SelectInput',
  component: SelectInput,
  parameters: {
    layout: 'centered',
  },
  tags: ['autodocs'],
  argTypes: {
    rowsPerPage: {
      control: 'select',
      options: ['5', '10', '15', '25', '50', '75', '100']
    },
    handleChangeRowsPerPage: { onChange: fn()}
  },
} satisfies Meta<typeof SelectInput>;

export default meta;
type Story = StoryObj<typeof meta>;

export const InUse: Story = {
  args: {
    rowsPerPage: 10,
    handleChangeRowsPerPage: (event) => {
      console.log(event.target.value)
    }
  },
};

And this is selectInput component:

function SelectInput({
  rowsPerPage,
  handleChangeRowsPerPage
}: {
  rowsPerPage: number;
  handleChangeRowsPerPage: (event: SelectChangeEvent) => void;
}) {
  return (
    <FormControl className="storybook-select-input">
      <InputLabel id="demo-simple-select-label">Rows per page</InputLabel>
      <Select
        labelId="demo-simple-select-label"
        id="demo-simple-select"
        value={rowsPerPage.toString()}
        label="Rows per page"
        onChange={handleChangeRowsPerPage}
      >
        <MenuItem value={5}>5</MenuItem>
        <MenuItem value={10}>10</MenuItem>
        <MenuItem value={15}>15</MenuItem>
        <MenuItem value={25}>25</MenuItem>
        <MenuItem value={50}>50</MenuItem>
        <MenuItem value={75}>75</MenuItem>
        <MenuItem value={100}>100</MenuItem>
      </Select>
    </FormControl>
  );
}

export default SelectInput;
1

There are 1 best solutions below

0
Adam Jenkins On

You're looking for useArgs

export const InUse: Story = {
  args: {
    rowsPerPage: 10,
  },
  render: function Render() => {
    const [args, updateArgs] = useArgs();
    return (
      <SelectInput 
        {...args} 
        handleChangeRowsPerPage={(event) => updateArgs({rowsPerPage:event.target.value})}  
      />
    );
  }
};