Skip to content

feat: useRadio 훅 추가 #9

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

Merged
merged 4 commits into from
May 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,31 @@ simple hook to change input components(uncontroll component) to controll compone
</div>
```

### useRadio

A hook to use the uncontrolled Radio component as a controlled component.

#### Generic

By using generics, you can configure the Radio component in a type-safe manner when using the hook.

```typescript
type RadioType = '🍕' | '🍔' | '🍟' | '🌭';
const { value, Radio, RadioGroup } = useRadio<RadioType>('🍕');
```

#### Function Arguments

You can set a `defaultValue`.

#### Return Values

`value`: The currently selected value among the Radios.

`Radio`: The Radio component. You can set the value in a type-safe manner through the hook. You can change the displayed value using children.

`RadioGroup`: A group that wraps multiple Radios.

### useInterval

simple hook to setInterval with React Component
Expand Down
31 changes: 31 additions & 0 deletions src/stories/useRadio/Docs.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Canvas, Meta, Description } from '@storybook/blocks';
import * as Radio from './Radio.stories';

<Meta of={Radio} />

# useRadio

비제어 컴포넌트 Radio를 제어 컴포넌트로 사용하기 위한 훅입니다.

## 제네릭

훅 사용시 제네릭을 사용하여 type safe하게 Radio를 구성할 수 있습니다.

```typescript
type RadioType = '🍕' | '🍔' | '🍟' | '🌭';
const { value, Radio, RadioGroup } = useRadio<RadioType>('🍕');
```

## 함수 인자

`defaultValue`를 설정할 수 있습니다.

## 반환값

`value` : 현재 Radio들 중 선택된 값입니다.

`Radio`: Radio 컴포넌트입니다. 훅을 통해 type safe하게 value를 설정할 수 있습니다. children으로 화면에 표기할 값을 변경할 수 있습니다.

`RadioGroup`: Radio들을 묶어줄 하나의 그룹입니다.

<Canvas of={Radio.defaultStory} />
21 changes: 21 additions & 0 deletions src/stories/useRadio/Radio.stories.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Meta, StoryObj } from '@storybook/react';
import Radio from './Radio';

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

export default meta;

type Story = StoryObj<typeof meta>;

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

type RadioType = '🍕' | '🍔' | '🍟' | '🌭';

export default function Radio() {
const { value, Radio, RadioGroup } = useRadio<RadioType>('🍕');
return (
<div>
<RadioGroup
style={{
border: 'none',
display: 'flex',
flexDirection: 'column',
fontSize: 35,
}}
>
<Radio value="🍕">🍕</Radio>
<Radio value="🍔">🍔</Radio>
<Radio value="🍟">🍟</Radio>
<Radio value="🌭">🌭</Radio>
</RadioGroup>
<div
style={{
fontSize: 20,
fontWeight: 600,
}}
>
오늘 점심은 {value}
</div>
</div>
);
}
61 changes: 61 additions & 0 deletions src/useRadio/useRadio.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import useRadio from './useRadio';
import React from 'react';
import { fireEvent, render, screen } from '@testing-library/react';

type RadioType = '1' | '2' | '3' | '4';

const RadioTestComponent = () => {
const { value, Radio, RadioGroup } = useRadio<RadioType>('1');
return (
<div>
<RadioGroup>
<Radio value="1">1</Radio>
<Radio value="2">2</Radio>
<Radio value="3">3</Radio>
<Radio value="4">4</Radio>
</RadioGroup>
<div role="result">{value}</div>
</div>
);
};

const RadioNonDefaultTestComponent = () => {
const { value, Radio, RadioGroup } = useRadio<RadioType>();
return (
<div>
<RadioGroup>
<Radio value="1">1</Radio>
<Radio value="2">2</Radio>
<Radio value="3">3</Radio>
<Radio value="4">4</Radio>
</RadioGroup>
<div role="result">{value}</div>
</div>
);
};
describe('useRadio 기능테스트', () => {
it('Radio가 선택되면 값을 변경할 수 있다.', async () => {
render(<RadioTestComponent />);
fireEvent.click(await screen.findByText('3'));
const [result] = await screen.findAllByRole('result');
expect(result.textContent).toBe('3');

fireEvent.click(await screen.findByText('1'));
expect(result.textContent).toBe('1');

fireEvent.click(await screen.findByText('2'));
expect(result.textContent).toBe('2');
});

it('Default 값이 없는 경우, check되지 않는 상태로 렌더링된다.', async () => {
const { container } = render(<RadioNonDefaultTestComponent />);
const result = await screen.findByRole('result');
expect(result.textContent).toBe('');

const labels = container.querySelectorAll('label');
labels.forEach((label) => {
const input = label.querySelector('input');
expect(input!.checked).toBeFalsy();
});
});
});
71 changes: 71 additions & 0 deletions src/useRadio/useRadio.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import React, { CSSProperties, ReactNode, createContext, useContext, useState } from 'react';

type RadioValue = string | number;
const RadioContext = createContext<[RadioValue | undefined, React.Dispatch<React.SetStateAction<RadioValue | undefined>>]>([
undefined,
() => {},
]);

const RadioGroup = <T extends RadioValue>({
radioState,
className,
style,
children,
}: {
radioState: [T | undefined, React.Dispatch<React.SetStateAction<T | undefined>>];
className?: string;
style?: CSSProperties;
children: ReactNode;
}) => {
return (
<fieldset className={className} style={style}>
<RadioContext.Provider value={radioState}>{children}</RadioContext.Provider>
</fieldset>
);
};
Comment on lines +9 to +25
Copy link
Contributor

Choose a reason for hiding this comment

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

- <RadioGroup>
-   <Radio />
- </RadioGroup>

+ <Radio>
+   <Radio.Value/>
+ </Radio>

이런식으로 compound 방식을 사용해도 좋을 것 같아요!
서로 연관된 Element임을 알 수 있고 구조를 파악하기 더 쉬울 것 같아요


const Radio = <T extends RadioValue>({
value,
className,
style,
children,
}: {
value: T;
className?: string;
style?: CSSProperties;
children: ReactNode;
}) => {
const [radioValue, setRadioValue] = useContext(RadioContext);

return (
<label>
<input
type="radio"
value={value}
onChange={() => setRadioValue(value)}
className={className}
style={style}
checked={value === radioValue}
/>
{children}
</label>
);
};

export default function useRadio<T extends RadioValue>(defaultValue?: T) {
const radioState = useState(defaultValue);

const RadioGroupWrapper = ({ className, style, children }: { className?: string; style?: CSSProperties; children: ReactNode }) => {
return (
<RadioGroup className={className} style={style} radioState={radioState}>
{children}
</RadioGroup>
);
};

return {
RadioGroup: RadioGroupWrapper,
Radio: Radio<T>,
value: radioState[0],
};
}
Loading