Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: develop useSwitch custom hook #20

Merged
merged 2 commits into from
May 27, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions src/stories/useSwitch/Docs.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { Canvas, Meta, Description } from '@storybook/blocks';
import * as SwitchStories from './Switch.stories';

<Meta of={SwitchStories} />

# useSwitch

useSwitch를 통해 선언적으로 Switch(or Toggle) 컴포넌트를 관리할 수 있습니다.

## 함수인자

defaultValue를 통해 초기 토글의 켬/꺼짐 상태를 결정할 수 있습니다.

## 반환값

### `isOn` (default `false`)
switch의 상태를 나타냅니다. switch가 켜져있으면 `true`, 아니면 `false`입니다.

### `on`
switch를 켜짐 상태로 전환합니다.

### `off`
switch를 꺼짐 상태로 전환합니다.

### `toggle`
switch의 켜진 상태를 반전시킵니다.

## 기본 사용 예시

```typescript
export default function Switch() {
import useSwitch from '../../useSwitch/useSwitch';
import React, { ChangeEventHandler } from 'react';

import './Switch.css';

export default function Switch() {
const sw = useSwitch(false);

const handleChangeSwitch: ChangeEventHandler<HTMLInputElement> = () => {
sw.toggle();
};

return (
<label className="switch">
<input type="checkbox" checked={sw.isOn} onChange={handleChangeSwitch} />
<span className="slider round"></span>
check
</label>
);
}
}
```

<Canvas of={SwitchStories.defaultStory} />
62 changes: 62 additions & 0 deletions src/stories/useSwitch/Switch.css
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Storybook 내부적으로 css 속성들이 겹치는 문제가 발생해서 vanilla extract를 도입하였는데요, 혹시 괜찮으시면 이후에 이 부분 내용이 바뀌어도 괜찮으신지 여쭤보고 싶습니다...!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

네 괜찮습니다

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

네 감사합니당

Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/* The switch - the box around the slider */
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}

/* Hide default HTML checkbox */
.switch input {
opacity: 0;
width: 0;
height: 0;
}

/* The slider */
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}

.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}

input:checked + .slider {
background-color: #2196F3;
}

input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}

/* Rounded sliders */
.slider.round {
border-radius: 34px;
}

.slider.round:before {
border-radius: 50%;
}
19 changes: 19 additions & 0 deletions src/stories/useSwitch/Switch.stories.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Meta, StoryObj } from '@storybook/react';
import Switch from './Switch';

const meta = {
title: 'hooks/useSwitch',
component: Switch,
parameters: {
layout: 'centered',
docs: {
canvas: {},
},
},
} satisfies Meta<typeof Switch>;

export default meta;

type Story = StoryObj<typeof meta>;

export const defaultStory: Story = {};
20 changes: 20 additions & 0 deletions src/stories/useSwitch/Switch.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import useSwitch from '../../useSwitch/useSwitch';
import React, { ChangeEventHandler } from 'react';

import './Switch.css';

export default function Switch() {
const sw = useSwitch(false);

const handleChangeSwitch: ChangeEventHandler<HTMLInputElement> = () => {
sw.toggle();
};

return (
<label className="switch">
<input type="checkbox" checked={sw.isOn} onChange={handleChangeSwitch} />
<span className="slider round"></span>
check
</label>
);
}
24 changes: 24 additions & 0 deletions src/useBoolean/_useBoolean.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import useBoolean from './useBoolean';
import { renderHook, act } from '@testing-library/react';

describe('useBoolean 기능테스트', () => {
it('useBoolean은 boolean상태를 나타내는 값과 그 boolean을 변경할 수 있는 값을 배열로 반환한다.', () => {
const { result } = renderHook(() => useBoolean(false));

expect(result.current[0]).toBe(false);
act(() => {
result.current[1](true);
});
expect(result.current[0]).toBe(true);
});

it('useBoolean은 초기값을 받으며 useBoolean의 초기값을 설정한다', () => {
const { result: resultFalse } = renderHook(() => useBoolean(false));
const { result: resultTrue } = renderHook(() => useBoolean(true));
const [maybeFalse] = resultFalse.current;
const [maybeTrue] = resultTrue.current;

expect(maybeFalse).toBe(false);
expect(maybeTrue).toBe(true);
});
});
7 changes: 7 additions & 0 deletions src/useBoolean/useBoolean.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { useState } from 'react';

export type UseSwitchReturn = ReturnType<typeof useBoolean>;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

혹시 여기 따로 타입지 정을 해주신 이유가 있을까용?
useSwitch 와 useBoolean모두 UseSwitchReturn이라는 이름으로 타입이 기재되어있어서 여쭤봅니다!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

앗 수정해야겠네요. 실수입니다


export default function useBoolean(defaultValue: boolean = false) {
return useState<boolean>(defaultValue);
}
32 changes: 32 additions & 0 deletions src/useSwitch/_useSwitch.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import useSwitch from './useSwitch';
import { renderHook, act } from '@testing-library/react';

describe('useSwitch 기능테스트', () => {
it('useSwitch는 스위치(혹은 토글)의 켜짐 상태와 켜짐상태를 조절할 수 있는 함수들을 반환한다.', () => {
const { result } = renderHook(() => useSwitch(false));

expect(result.current.isOn).toBe(false);
act(() => {
result.current.on();
});
expect(result.current.isOn).toBe(true);
act(() => {
result.current.off();
});
expect(result.current.isOn).toBe(false);
act(() => {
result.current.toggle();
});
expect(result.current.isOn).toBe(true);
});

it('useSwitch는 초기값을 파라미터로 받는다.', () => {
const { result: resultFalse } = renderHook(() => useSwitch(false));
const { result: resultTrue } = renderHook(() => useSwitch(true));
const maybeFalse = resultFalse.current.isOn;
const maybeTrue = resultTrue.current.isOn;

expect(maybeFalse).toBe(false);
expect(maybeTrue).toBe(true);
});
});
27 changes: 27 additions & 0 deletions src/useSwitch/useSwitch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import useBoolean from '../useBoolean/useBoolean';
import { useCallback } from 'react';

export type UseSwitchReturn = ReturnType<typeof useSwitch>;

export default function useSwitch(defaultValue: boolean = false) {
const [isOn, setOn] = useBoolean(defaultValue);

const on = useCallback(() => {
setOn(true);
}, [setOn]);

const off = useCallback(() => {
setOn(false);
}, [setOn]);

const toggle = useCallback(() => {
setOn((prev) => !prev);
}, [setOn]);

return {
isOn,
on,
off,
toggle,
};
}
Loading