import { Dictionary } from "lodash"; import React from "react"; import { SPACE_BETWEEN_HORIZONTALLY } from "../../../utils/styles"; import Select from "../Select/Select"; export type formInput = { name: string; label: string; validationMessage: string; inputProps: React.DetailedHTMLProps, HTMLInputElement>; options?: Dictionary; }; export type FormProps = { onSubmitForm: (fields: Dictionary) => void; submitFormButtonText: string; submitFormButtonColor?: string; formInputs: formInput[]; }; type FormState = { fields: Dictionary; }; // Generates a Form Message for every invalid matcher. This is used instead of manually creating // a Form Message for every invalid case. // function formMessageMatchAll(message: string) { // const invalidMatchers: ReactForm.ValidityMatcher[] = [ // "badInput", // "patternMismatch", // "rangeOverflow", // "rangeUnderflow", // "stepMismatch", // "tooLong", // "tooShort", // "typeMismatch", // "valueMissing" // ]; // return invalidMatchers.map((matcher) => ( //
// {message} //
// )); // } export default class Form extends React.Component { clickedButtonName = ""; constructor(props: FormProps | Readonly) { super(props); // initialize state from defaultValues provided const fields: { [index: string]: any } = {}; props.formInputs.forEach((formInput) => { if (formInput.inputProps.defaultValue) fields[formInput.name] = formInput.inputProps.defaultValue; }); this.state = { fields }; } handleFormInput = (event: React.ChangeEvent) => { const { name, value } = event.target; const fields = this.state.fields; this.setState({ fields: { ...fields, ...{ [name]: value } } }); }; onSubmit = (event: any) => { event.preventDefault(); if (this.clickedButtonName == this.props.submitFormButtonText) this.props.onSubmitForm(this.state.fields); }; handleClick = (event: any) => { this.clickedButtonName = event.target.name; }; render() { // console.log("new Form state: " + JSON.stringify(this.state, null, 4)) const { formInputs, submitFormButtonText, submitFormButtonColor } = this.props; return (
{formInputs.map((formInput) => { return (
{/* Range Input additional label */} {formInput.inputProps.type && formInput.inputProps.type === "range" ? ( ) : ( {formInput.label} )} {/* Validations */} {/* {formMessageMatchAll(formInput.validationMessage)} */} {/* Input */} {formInput.options !== undefined ? ( )}
); })}
); } }