Skip to content

Instantly share code, notes, and snippets.

@royib
Created February 22, 2020 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save royib/acf6befca51c19c4d77844124e2a5dd1 to your computer and use it in GitHub Desktop.
Save royib/acf6befca51c19c4d77844124e2a5dd1 to your computer and use it in GitHub Desktop.
import React from "react";
import FormContext from "./FormContext";
class FormField extends React.Component {
async componentDidMount() {
let { name, validators = [] } = this.props;
const { validateField, getFieldValue } = this.context;
// set default value
const newValue = getFieldValue({ name });
//update validation state
await validateField(newValue, name, validators);
}
render() {
const { name, validators, Component, ...otherProps } = this.props;
const {
setFieldValue,
getFieldValue,
validateField,
getFieldValidationState,
getFieldTouchedState,
setFieldTouchState,
submitOccurred
} = this.context;
const value = getFieldValue({ name }) || "";
const validationState = getFieldValidationState({ name });
const touchedState = getFieldTouchedState({ name });
const error =
validationState &&
!validationState.valid &&
(touchedState || submitOccurred);
const validationText =
validationState &&
(touchedState || submitOccurred) &&
validationState.validationText;
const onChange = newValue => {
setFieldValue(name, newValue);
};
return (
<Component
{...otherProps}
onChange={onChange}
validateField={newValue => {
validateField(newValue, name, validators);
setFieldTouchState(name);
}}
value={value}
error={error}
name={name}
validationText={validationText}
/>
);
}
}
FormField.contextType = FormContext;
export default FormField;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment