import React, { ReactFragment } from 'react'; import Input from '@/components/input/input'; import { scopedClassMaker } from '@/helper/classes'; import './form.scss'; export interface FormValue { [K: string]: string; } interface Props { value: FormValue; fields: Array<{ name: string; label: string; input: { type: string } }>; buttons: ReactFragment; onSubmit: React.FormEventHandler; onChange: (value: FormValue) => void; errors: { [K: string]: string[] }; errorsDisplayMode: 'first' | 'all'; } const scopedClass = scopedClassMaker('gulu-form'); const sc = scopedClass; const Form: React.FunctionComponent = props => { const formData = props.value; const onSubmit: React.FormEventHandler = e => { e.preventDefault(); props.onSubmit(e); }; const onInputChange = (name: string, value: string) => { const newFormValue = { ...formData, [name]: value }; props.onChange(newFormValue); }; const errorsDisplay = (errors: string[] | undefined) => { if (errors === undefined) { return  ; } if (props.errorsDisplayMode === 'first') { return errors[0]; } else { return errors.join(','); } }; return (
{props.fields.map(item => ( ))}
{item.label} onInputChange(item.name, e.target.value)} />
{errorsDisplay(props.errors[item.name])}
{props.buttons}
); }; Form.defaultProps = { errorsDisplayMode: 'first', }; export default Form;