import React, { useState, useRef, useImperativeHandle } from 'react'; import { getFormData } from '../../utils/getFormData'; import { FormCheck, IFormCheck } from './FormCheck'; import { FormControl, IFormControl } from './FormControl'; import { FormGroup, IFormGroup } from './FormGroup'; import { FormRow, IFormRow } from './FormRow'; import { FormLabel, IFormLabel } from './FormLabel'; export interface IForm extends React.FormHTMLAttributes { className?: string; inline?: boolean; resetOnSubmit?: boolean; validated?: boolean; onSubmit?(data: any): void; [x: string]: any; } export interface IFormWithSubComponents extends React.ForwardRefExoticComponent { Check: React.FC; Control: React.FC; Group: React.FC; Label: React.FC; Row: React.FC; } export const Form = React.forwardRef((props, forwardRef) => { const { className, inline, onSubmit, validated = false, resetOnSubmit, ...otherProps } = props; const [wasValidated, setWasValidated] = useState(false); const formRef = useRef(null); useImperativeHandle(forwardRef, () => formRef.current); function handleCheckValidity() { setWasValidated(true); if (formRef.current.checkValidity() === false) { return; } else { onSubmit(getFormData(formRef.current)); setWasValidated(false); if (resetOnSubmit) { formRef.current.reset(); } } } function handleSubmit(e: React.FormEvent) { e.stopPropagation(); e.preventDefault(); if (onSubmit) { handleCheckValidity(); } } function classNames() { let classList = 'b-form'; if (inline) classList += `b-form-inline`; if (wasValidated || validated) classList += ` b-form-was-validated`; if (className) classList += ` ${className}`; return classList; } return (
{props.children}
); }) as IFormWithSubComponents; Form.Check = FormCheck; Form.Control = FormControl; Form.Group = FormGroup; Form.Label = FormLabel; Form.Row = FormRow;