import React, { memo, useEffect, useState, ReactNode } from 'react'; import isEmpty from 'lodash/isEmpty'; import isEqual from 'lodash/isEqual'; import Grid from '@material-ui/core/Grid'; import Autocomplete from '@material-ui/lab/Autocomplete'; import TextField, { StandardTextFieldProps } from '@material-ui/core/TextField'; import MenuItem from '@material-ui/core/MenuItem'; import Button from './../Button'; import './Form.css'; /** * We can improve this component in two way: * 1. Export IField interface (many app already use a copy of it, make code redundant) * 2. Improve type: we have too much "any" in the code! */ interface IField extends StandardTextFieldProps { fieldName: string; icon?: ReactNode; autocomplete?: boolean; items?: any; // TODO: improve it } export interface IProps { fields: IField[]; onSubmit?: (fields: any) => any; submitLabel?: string; onValidate?: (fields: any) => any; onChange?: (fields: any) => any; children: ReactNode; } export function Form({ fields, onSubmit, submitLabel, onValidate, onChange, children }: IProps) { const [fieldsState, changeFieldsState] = useState({}); const [isValid, changeIsValid] = useState(true); useEffect(() => { let newFields = { ...fieldsState }; fields.forEach((f) => { newFields = { ...newFields, [f.fieldName]: f.value }; }); /** * If doesn't exist any difference, i don't need state update */ if (isEqual(newFields, fieldsState)) { return; } changeFieldsState(newFields); }, [fields]); useEffect(() => { if (onValidate) { changeIsValid(onValidate(fieldsState)); } }, [fieldsState]); const handleSubmit = (e: any) => { e.preventDefault(); if (!onSubmit || !isValid) { return; } onSubmit(fieldsState); }; return (
{fields?.map( ({ fieldName, autocomplete, items, fullWidth, ...rest }) => { const commonProps: any = { ...rest, variant: 'outlined', InputLabelProps: { shrink: true }, fullWidth: true, value: fieldsState[fieldName] }; return ( {!isEmpty(items) && autocomplete ? ( changeFieldsState({ ...fieldsState, [fieldName]: target?.value }) } options={items} getOptionLabel={(option) => option.label} value={{ ...items.find( (i: any) => i.value === fieldsState[fieldName] ) }} renderInput={(params: any) => ( )} disableClearable /> ) : ( { const newFields = { ...fieldsState, [fieldName]: e.target.value }; changeFieldsState(newFields); if (onChange) { onChange(newFields); } }} > {items?.map((item: any) => ( {item.label} ))} )} ); } )} {children} {onSubmit && ( )}
); } export default memo(Form);