Created
February 22, 2020 19:49
-
-
Save royib/acf6befca51c19c4d77844124e2a5dd1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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