Skip to content

Instantly share code, notes, and snippets.

@phucdph
Created April 4, 2020 16:04
Show Gist options
  • Select an option

  • Save phucdph/143c08fd2dd43f3f4ac34f5599c4a0b0 to your computer and use it in GitHub Desktop.

Select an option

Save phucdph/143c08fd2dd43f3f4ac34f5599c4a0b0 to your computer and use it in GitHub Desktop.
[Formik] Custom Field
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