Add Radio and RadioGroup component
[MAILPOET-2773]
This commit is contained in:
51
assets/js/src/common/form/radio/group.tsx
Normal file
51
assets/js/src/common/form/radio/group.tsx
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
import React, { InputHTMLAttributes, useState } from 'react';
|
||||||
|
import Radio from './radio';
|
||||||
|
|
||||||
|
type RadioValueType = string | string[] | number;
|
||||||
|
|
||||||
|
type RadioProps = InputHTMLAttributes<HTMLInputElement> & {
|
||||||
|
label: string,
|
||||||
|
}
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
name: string,
|
||||||
|
options: RadioProps[],
|
||||||
|
defaultValue?: RadioValueType,
|
||||||
|
isFullWidth?: boolean,
|
||||||
|
onChange?: (RadioValueType) => void,
|
||||||
|
};
|
||||||
|
|
||||||
|
const RadioGroup = ({
|
||||||
|
name,
|
||||||
|
options,
|
||||||
|
defaultValue,
|
||||||
|
isFullWidth,
|
||||||
|
onChange,
|
||||||
|
}: Props) => {
|
||||||
|
const [currentValue, setCurrentValue] = useState(defaultValue);
|
||||||
|
|
||||||
|
const handleChange = (value: RadioValueType) => {
|
||||||
|
setCurrentValue(value);
|
||||||
|
onChange(value);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
{options.map(({ label, value, ...attributes }: RadioProps) => (
|
||||||
|
<Radio
|
||||||
|
checked={currentValue === value}
|
||||||
|
key={label}
|
||||||
|
name={name}
|
||||||
|
value={value}
|
||||||
|
onChange={() => handleChange(value)}
|
||||||
|
isFullWidth={isFullWidth}
|
||||||
|
{...attributes} // eslint-disable-line react/jsx-props-no-spreading
|
||||||
|
>
|
||||||
|
{label}
|
||||||
|
</Radio>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default RadioGroup;
|
34
assets/js/src/common/form/radio/radio.tsx
Normal file
34
assets/js/src/common/form/radio/radio.tsx
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import React, { InputHTMLAttributes } from 'react';
|
||||||
|
import classnames from 'classnames';
|
||||||
|
|
||||||
|
type Props = InputHTMLAttributes<HTMLInputElement> & {
|
||||||
|
children?: React.ReactNode,
|
||||||
|
isFullWidth?: boolean,
|
||||||
|
onChange?: (boolean) => void,
|
||||||
|
};
|
||||||
|
|
||||||
|
const Radio = ({
|
||||||
|
children,
|
||||||
|
isFullWidth,
|
||||||
|
onChange,
|
||||||
|
...attributes
|
||||||
|
}: Props) => (
|
||||||
|
<label
|
||||||
|
className={
|
||||||
|
classnames({
|
||||||
|
'mailpoet-form-radio': true,
|
||||||
|
'mailpoet-full-width': isFullWidth,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
onChange={(e) => onChange(e.target.checked)}
|
||||||
|
{...attributes}
|
||||||
|
/>
|
||||||
|
<span className="mailpoet-form-radio-control" />
|
||||||
|
{children}
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
|
||||||
|
export default Radio;
|
Reference in New Issue
Block a user