-
Notifications
You must be signed in to change notification settings - Fork 4
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
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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} /> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: {}, | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | ||
); | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
}); | ||
}); | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | ||
); | ||
}; | ||
|
||
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], | ||
}; | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
이런식으로 compound 방식을 사용해도 좋을 것 같아요!
서로 연관된 Element임을 알 수 있고 구조를 파악하기 더 쉬울 것 같아요