-
-
Save chulanovskyi/c7d67deaf7f62c9aaaffe0cd2c09db74 to your computer and use it in GitHub Desktop.
Sign-in Form
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 cn from 'clsx'; | |
import * as React from 'react'; | |
import { useEffect, useRef } from 'react'; | |
import { InjectedFormikProps, Form, Field, withFormik, FormikActions } from 'formik'; | |
import { Button, Loader, Icon, colors } from 'vue-components'; | |
import { AnimatedInput } from 'components'; | |
import { ISignInFormValues } from 'models/internal'; | |
import { useSubmitOnEnter } from 'hooks/useSubmitOnEnter'; | |
export interface ISignInFormProps { | |
onSignIn(values: ISignInFormValues, formActions: Partial<FormikActions<ISignInFormValues>>): void; | |
initialValues?: ISignInFormValues; | |
} | |
const SignInForm = (props: InjectedFormikProps<ISignInFormProps, ISignInFormValues>) => { | |
const { status, values, setFieldValue, isValid, isSubmitting, submitForm, setStatus } = props; | |
const formClass = cn('sign-in-form-container', { 'submit-failed': status }); | |
const onClearField = fieldName => setFieldValue(fieldName, ''); | |
useSubmitOnEnter(submitForm); | |
const usernameRef = useRef<HTMLInputElement>(); | |
useEffect(() => { | |
setStatus(null); | |
}, [values.username, values.password, setStatus]); | |
useEffect(() => { | |
usernameRef.current.focus(); | |
}, [usernameRef]); | |
return ( | |
<Form className={formClass}> | |
<Field | |
component={AnimatedInput} | |
name="username" | |
label="USERNAME or EMAIL ADDRESS" | |
onClear={onClearField} | |
innerRef={usernameRef} | |
/> | |
<Field | |
component={AnimatedInput} | |
name="password" | |
label="PASSWORD" | |
onClear={onClearField} | |
type="password" | |
/> | |
{status ? ( | |
<div className="invalid-user"> | |
<Icon icon="fas fa-exclamation-circle" color={colors.$white} /> | |
<div className="title"> | |
<span>Sorry</span> | |
<span>Invalid user and password combination</span> | |
</div> | |
</div> | |
) : ( | |
<Button | |
title={isSubmitting ? <Loader config={{ color: colors.$white }} /> : 'Sign In'} | |
action={submitForm} | |
disabled={!isValid || isSubmitting} | |
/> | |
)} | |
</Form> | |
); | |
}; | |
export default withFormik<ISignInFormProps, ISignInFormValues>({ | |
mapPropsToValues: ({ initialValues }) => ({ | |
username: '', | |
password: '', | |
...initialValues | |
}), | |
validate: ({ username, password }) => { | |
if (!username || !password) { | |
return { error: 'Please field the fields' }; | |
} | |
}, | |
handleSubmit: (values, { props, resetForm, setStatus, setSubmitting }) => { | |
props.onSignIn(values, { | |
resetForm, | |
setStatus, | |
setSubmitting | |
}); | |
} | |
})(SignInForm); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment