Created
April 4, 2020 16:04
-
-
Save phucdph/143c08fd2dd43f3f4ac34f5599c4a0b0 to your computer and use it in GitHub Desktop.
[Formik] Custom Field
This file contains hidden or 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 { FieldAttributes } from "formik"; | |
| import * as React from "react"; | |
| import { get } from "lodash"; | |
| import { TextField as BaseTextField } from "@material-ui/core"; | |
| interface IProps extends FieldAttributes<any> {} | |
| const TextField = (props: IProps) => { | |
| const { field, form, ...rest } = props; | |
| const { name } = field; | |
| const { setFieldValue, setFieldTouched, touched, errors } = form; | |
| const onInputChange = React.useCallback( | |
| ({ target: { value } }: any) => setFieldValue(name, value), | |
| [name, setFieldValue] | |
| ); | |
| const onBlur = React.useCallback(() => setFieldTouched(name, true), [ | |
| setFieldTouched, | |
| name | |
| ]); | |
| const error = React.useMemo(() => get(touched, name) && !!get(errors, name), [ | |
| name, | |
| touched, | |
| errors | |
| ]); | |
| const errorMessage = React.useMemo( | |
| () => (get(touched, name) ? get(errors, name) : undefined), | |
| [name, touched, errors] | |
| ); | |
| return ( | |
| <BaseTextField | |
| error={error} | |
| name={name} | |
| id={name} | |
| {...field} | |
| {...rest} | |
| helperText={errorMessage} | |
| onBlur={onBlur} | |
| onChange={onInputChange} | |
| /> | |
| ); | |
| }; | |
| export default TextField; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment