Add Radio and RadioGroup component

[MAILPOET-2773]
This commit is contained in:
Ján Mikláš
2020-05-18 16:09:15 +02:00
committed by Veljko V
parent 7286bcf49d
commit 5fc32d89f2
2 changed files with 85 additions and 0 deletions

View 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;

View 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;