Skip to content

Commit 11d45fd

Browse files
committed
Update RadioPrimitive component to manage checked state
1 parent 14c99fa commit 11d45fd

File tree

2 files changed

+12
-22
lines changed

2 files changed

+12
-22
lines changed

src/core/primitives/Radio/RadioPrimitive.stories.tsx

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,11 @@ export default {
99

1010
<div className='flex flex-col gap-2'>
1111
<span>
12-
<RadioPrimitive name='radio' value='radio' onClick={() => {}} />
12+
<RadioPrimitive name='radio' value='radio' checked={true} />
1313
<label htmlFor='radio'>Radio 1</label>
1414
</span>
1515
<span>
16-
<RadioPrimitive name='radio' value='radio2' onClick={() => {}} />
16+
<RadioPrimitive name='radio' value='radio2'/>
1717
<label htmlFor='radio2'>Radio 2</label>
1818
</span>
1919
</div>
@@ -23,8 +23,6 @@ export default {
2323

2424
export const All = {
2525
args: {
26-
checked: true,
27-
value: 'radio',
2826
onClick: (data: any) => {
2927
console.log('data', data);
3028
}

src/core/primitives/Radio/index.tsx

Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,25 @@
1-
import React from 'react';
1+
import React, { useState } from 'react';
22
import Primitive from '~/core/primitives/Primitive';
33

4-
type RadioPrimitiveProps = {
5-
onClick: (data: any) => void;
6-
onChange: (data: any) => void;
7-
checked: boolean;
4+
export type RadioPrimitiveProps = {
5+
onClick?: (data: any) => void;
6+
onChange?: (data: any) => void;
7+
checked?: boolean;
88
name: string;
99
value: string;
1010
};
1111

1212
const RadioPrimitive = ({ name = '', value = '', checked = false, onClick, onChange, ...props }:RadioPrimitiveProps) => {
13+
const [isChecked, setIsChecked] = useState(checked);
1314
const dataAttributes = {
14-
'data-checked': checked.toString()
15-
};
16-
17-
const handleOnClick = (event: React.MouseEvent<HTMLInputElement>) => {
18-
const isChecked = event.target?.checked;
19-
if (typeof onClick === 'function') {
20-
onClick({
21-
value,
22-
checked: isChecked
23-
});
24-
}
15+
'data-checked': isChecked.toString()
2516
};
2617

2718
const handleOnChange = (event: React.ChangeEvent<HTMLInputElement>) => {
2819
const isChecked = event.target.checked;
29-
20+
console.log(isChecked);
3021
if (typeof onChange === 'function') {
22+
setIsChecked(isChecked);
3123
onChange({
3224
value,
3325
checked: isChecked
@@ -36,7 +28,7 @@ const RadioPrimitive = ({ name = '', value = '', checked = false, onClick, onCha
3628
};
3729

3830
return (
39-
<Primitive.input id={value} type='radio' value={value} name={name} onClick={handleOnClick} onChange={handleOnChange} {...props} {...dataAttributes}/>
31+
<Primitive.input id={value} type='radio' value={value} name={name} onChange={handleOnChange} {...props} {...dataAttributes}/>
4032
);
4133
};
4234

0 commit comments

Comments
 (0)