Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

react-hook-form #33

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion template.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,20 @@
"@emotion/styled": "^11.10.5",
"@formatjs/intl-pluralrules": "5.1.4",
"@formatjs/intl-relativetimeformat": "11.1.4",
"@hookform/resolvers": "^3.1.0",
"@mui/icons-material": "^5.11.0",
"@mui/lab": "^5.0.0-alpha.115",
"@mui/material": "^5.11.4",
"axios": "^1.3.4",
"axios-auth-refresh": "^3.3.6",
"dayjs": "^1.10.7",
"formik": "^2.2.9",
"intl": "^1.2.5",
"license-checker-webpack-plugin": "^0.2.1",
"lodash": "^4.17.21",
"query-string": "^7.0.1",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-hook-form": "^7.43.9",
"react-intl": "6.2.1",
"react-query": "^3.39.3",
"react-router": "^6.4.2",
Expand Down
2 changes: 1 addition & 1 deletion template/src/components/app/router/AppRouter.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ReactQueryDevtools } from "react-query/devtools";
import { BrowserRouter, Outlet, Route, Routes } from "react-router-dom";
import { BASE_NAME, DEBUG_PUBLIC_DASHBOARD, LOADING_INDICATOR_DELAY_MS } from "../../../config";
import { useQueryParams } from "../../../hooks/useQueryParams";
import { IDebugTab, useDebugStore } from "../../../stores/debugStore";
import { useGeneralStore } from "../../../stores/generalStore";
import { AuthLoginSite } from "../../auth/sites/AuthLoginSite";
Expand All @@ -16,7 +17,6 @@ import { NoAuthOnlyRoute } from "./NoAuthOnlyRoute";
import { PrivateRoute } from "./PrivateRoute";
import { RoutingManager } from "./RoutingManager";
import ScrollToTop from "./ScrollToTop";
import { useQueryParams } from "../../../hooks/useQueryParams";

export const AppRouter = () => {
const isLoading = useGeneralStore((state) => state.isLoading);
Expand Down
114 changes: 56 additions & 58 deletions template/src/components/auth/sites/AuthLoginSite.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { yupResolver } from "@hookform/resolvers/yup";
import { Button } from "@mui/material";
import { AxiosError } from "axios";
import { Field, Form, Formik } from "formik";
import * as React from "react";
import { useForm } from "react-hook-form";
import * as Yup from "yup";
import { t } from "../../../i18n/util";
import { useLogin } from "../../../network/api/useLogin";
Expand All @@ -19,6 +20,25 @@ interface ILoginValues {
}

export const AuthLoginSite = () => {
const { handleSubmit, formState, control } = useForm<ILoginValues>({
defaultValues: {
email: "",
password: "",
},
mode: "onTouched",
resolver: yupResolver(
Yup.object().shape({
email: Yup.string()
.email(t("screen.login.form.email.validation_error"))
.required(t("screen.login.form.email.validation_error"))
.trim(),
password: Yup.string()
.min(6, t("screen.login.form.password.validation_error"))
.required(t("screen.login.form.password.validation_error")),
}),
),
});

const [error, setError] = React.useState<string>();
const pushRoute = usePushRoute();

Expand All @@ -28,7 +48,7 @@ export const AuthLoginSite = () => {

const setIsLoading = useGeneralStore((state) => state.setIsLoading);

const handleSubmit = async (model: ILoginValues) => {
const onSubmit = async (model: ILoginValues) => {
setIsLoading(true);
setError("");

Expand Down Expand Up @@ -84,64 +104,42 @@ export const AuthLoginSite = () => {
>
{t("screen.login.title")}
</div>
<div style={{ padding: 24, border: `1px solid ${Colors.PRIMARY_COLOR}`, borderTop: "none" }}>
<Formik
initialValues={{
email: "",
password: "",

<form
onSubmit={handleSubmit(onSubmit)}
style={{ padding: 24, border: `1px solid ${Colors.PRIMARY_COLOR}`, borderTop: "none" }}
>
<CustomInputField
name="email"
control={control}
label={t("screen.login.form.email.label")}
type="email"
autoComplete="username"
/>

<CustomInputField
name="password"
control={control}
label={t("screen.login.form.password.label")}
type="password"
autoComplete="current-password"
/>

{error && <div style={{ color: Colors.ERROR, fontSize: 14 }}>{error}</div>}
<Button
variant="contained"
style={{
boxShadow: "none",
borderRadius: 24,
marginTop: 24,
}}
onSubmit={handleSubmit}
validationSchema={Yup.object().shape({
email: Yup.string()
.email(t("screen.login.form.email.validation_error"))
.required(t("screen.login.form.email.validation_error"))
.trim(),
password: Yup.string()
.min(6, t("screen.login.form.password.validation_error"))
.required(t("screen.login.form.password.validation_error")),
})}
validateOnBlur
fullWidth
disabled={formState.isSubmitting}
type="submit"
>
{({ errors, touched, isSubmitting }) => (
<Form>
<Field
component={CustomInputField}
label={t("screen.login.form.email.label")}
name="email"
type="email"
required
autoComplete="username"
errorMessage={errors.email}
isTouched={touched.email}
/>
<Field
component={CustomInputField}
label={t("screen.login.form.password.label")}
name="password"
type="password"
required
autoComplete="current-password"
errorMessage={errors.password}
isTouched={touched.password}
/>
{error && <div style={{ color: Colors.ERROR, fontSize: 14 }}>{error}</div>}
<Button
variant="contained"
style={{
boxShadow: "none",
borderRadius: 24,
marginTop: 24,
}}
fullWidth
disabled={isSubmitting}
type="submit"
>
{t("screen.login.form.submit")}
</Button>
</Form>
)}
</Formik>
</div>
{t("screen.login.form.submit")}
</Button>
</form>
</div>
</div>
);
Expand Down
40 changes: 20 additions & 20 deletions template/src/components/ui/CustomInputField.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
import { MenuItem, TextField, TextFieldProps } from "@mui/material";
import { FieldInputProps, FormikState, getIn } from "formik";
import * as React from "react";
import { FieldValues, UseControllerProps, useController } from "react-hook-form";
import { FieldError } from "./FieldError";

type IProps = TextFieldProps & {
field: FieldInputProps<string>;
onChange?: () => void;
form: FormikState<any>;
showValidationErrorText?: boolean;
selectOptions?: { value: string; label: string }[];
};
type IProps<T extends FieldValues> = TextFieldProps &
UseControllerProps<T> & {
onChange?: () => void;
showValidationErrorText?: boolean;
selectOptions?: { value: string; label: string }[];
};

export const CustomInputField = ({
export const CustomInputField = <T extends FieldValues>({
style,
label,
type,
Expand All @@ -20,16 +19,17 @@ export const CustomInputField = ({
minRows,
maxRows,
required,
form,
field,
name,
control,
"aria-label": ariaLabel,
placeholder,
showValidationErrorText = true,
selectOptions,
onChange,
}: IProps) => {
const fieldError = getIn(form.errors, field.name);
const showError = getIn(form.touched, field.name) && !!fieldError;
}: IProps<T>) => {
const { field, fieldState } = useController({ control, name: name ?? "" });

const fieldError = fieldState.error?.message;

const handleChange = (event: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => {
field.onChange(event);
Expand All @@ -42,14 +42,10 @@ export const CustomInputField = ({
<TextField
select={!!selectOptions}
label={required ? `${label} *` : label}
value={field.value}
name={field.name}
onBlur={field.onBlur}
onChange={handleChange}
fullWidth
type={type}
autoComplete={autoComplete}
error={showError}
error={!!fieldError}
margin="dense"
aria-label={ariaLabel}
variant="outlined"
Expand All @@ -60,14 +56,18 @@ export const CustomInputField = ({
// For date inputs shrink does not work correctly so explicitly set it.
// See here: https://mui.com/material-ui/react-text-field/#shrink
InputLabelProps={type === "date" ? { shrink: true } : undefined}
// Injects name, onChange, onBlur, value, ref
// So if you override an of these you have to put it after this
{...field}
onChange={handleChange}
>
{selectOptions?.map((selectOption) => (
<MenuItem key={selectOption.value} value={selectOption.value}>
{selectOption.label}
</MenuItem>
))}
</TextField>
{showValidationErrorText && <FieldError>{showError ? fieldError : ""}</FieldError>}
{showValidationErrorText && <FieldError>{fieldError}</FieldError>}
</div>
);
};