Storybook - Actions 애드온 (3)

1 minute read

이번에는 Storybook의 Actions 애드온에 대해서 알아보도록 하겠습니다.



Actions 애드온?

actions 애드온은 컴포넌트를 통해 발생한 이벤트 즉, 특정 함수가 호출될때 어떤 함수가 호출 되었는지, 그리고 함수에 어떠한 파라미터를 넣고 호출 했는지에 대한 정보를 확인할 수 있게 도와주는 애드온입니다.

간단한 컴포넌트 함수를 호출하거나, 라우터 이벤트시에 주소 변경 확인, 스토어 데이터의 dispatch 를 mocking 하여 액션의 정보 보기 등의 기능을 수행할 수 있습니다.

더 자세한 내용을 확인하시려면 공식 페이지에서 Action 애드온의 기능을 참고하세요.



Actions 사용하기

기본적으로 Storybook을 설치하면 Actions 기능이 기본으로 적용되어 있습니다. 따라서 추가적인 설치를 하지 않아도 됩니다.

그럼 지금부터 Actions 를 사용하기위해 Button 컴포넌트에 특정 이벤트를 연결해 봅시다. 버튼을 클릭하면 버튼의 색이 변경되는 함수를 만들어 보겠습니다.

// button/index.js

import React, {useState} from 'react';
import './Button.css'

function Button ({title, active, onActiveHandler}) {

  const [onActive, setActive] = useState(active);

  function setActiveHandler() {
    setActive(!onActive);
    onActiveHandler(onActive);
  }

  return (
    <button 
      type="button" 
      class={`${(onActive) ? 'on' : ''}`} 
      onClick={setActiveHandler}
     >{title}</button>
  );
}

export default Button;
}


React hook 인 useState를 이용해 컴포넌트의 onActive 라는 state를 생성합니다.
그리고 사용자가 버튼을 클릭하면 onActive 값이 true/false 스위칭 되면서 버튼의 색상이 변경되도록 설정합니다.

그럼 Button.storybook.js 에 해당 Actions를 정의합니다.

import React from 'react';
import { withKnobs, text, boolean } from '@storybook/addon-knobs';
import { action } from '@storybook/addon-actions';

import Button from './index';

export default {
  title: 'Button Component',
  component: Button,
  decorators: [withKnobs],
};

export const ButtonComponent = () => {
  let onActive = false;

  return (
    <Button 
      title={text('타이틀', '안녕하세요')} 
      active={boolean('버튼 확성', false)}
      onActiveHandler={action('클릭', !onActive)}
    />
  )
};

ButtonComponent.story = {
  name: 'Button',
};


@storybook/addon-actions’ 의 action 함수를 불러와 Button 컴포넌트의 onActiveHandler에 action(!onActive) 값으로 연결합니다. 그리고 Storybook 화면을 보시면 하단의 Actions 탭 화면으로 전환하고 위의 버튼을 클릭하시면 함수가 호출되면서 사용되는 값을 확인할 수 있습니다.



위의 화면처럼 함수 호출과 값이 표시된다면 성공입니다.

actions (‘이벤트 이름’, ‘값’) 의 형태로 호출하면 Storybook 화면에서 해당 이벤트 Actions를 쉽게 확인할 수 있습니다.

Tags:

Categories:

Updated:

 

 

Leave a comment