Forgot Password
Customizable set of React forgot password components that validate against a default or custom Zod schema. Accepts custom fields and includes reset request, token submission and confirmation views as needed.
Features
- Displays and handles client and serverside errors
- Custom fields and schema
- Show success components and/or provide onSuccess functions to redirect, set state, etc.
- Custom header/footer
- Loader (default or custom)
- Show a link to login instead
- Client router support for links
- Toast support
Install
npm install @unleashit/forgot-password
Required peer dependencies: react, react-hook-form and zod.
Password Reset Request Example
import ForgotPassword, {
FormValues,
ServerResponse,
} from '@unleashit/forgot-password';
function ForgotPasswordDemo() {
const forgotPasswordHandler = async (
values: FormValues,
): Promise<ServerResponse> => {
return await fetch('https://api.example.com/reset-request', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(values),
}).then((resp) => resp.json());
};
const onSuccess = (resp: ServerResponse) => {
console.log(resp);
};
return (
<ForgotPassword handler={forgotPasswordHandler} onSuccess={onSuccess} />
);
}
Note that onSuccess
is optional. By default, the user will be shown a generic success message as long as the server returns a success
boolean. If you provide an successMessage
prop, you can override it or set false
to turn off.
Password Reset Example
import ForgotPasswordReset, {
FormValues,
ServerResponse,
} from '@unleashit/forgot-password';
function ForgotPasswordResetDemo() {
const forgotPasswordResetHandler = async (
values: FormValues,
): Promise<ServerResponse> => {
const [token, userid] = new URL(window.location.href).pathname
.split('/')
.filter(Boolean)
.reverse();
return await fetch(
`https://api.example.com/password-reset/${userid}/${token}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(values),
},
).then((resp) => resp.json());
};
const onSuccess = (resp: ServerResponse) => {
console.log(resp);
};
return (
<ForgotPasswordReset
handler={forgotPasswordResetHandler}
onSuccess={onSuccess}
/>
);
}
In this example, the userId and authorization token are taken from the url under the assumption the user arrived from a link sent via email or SMS. By default (can be customized or turned off with a successMessage
prop), a success message will be shown to the user if the server returns a positive response with no errors.
Custom Fields
It's possible to replace the default fields with custom fields by adding customFields
and customSchema
props. On submission and after passing validation, the handler will be called with the field values.
customFields
is an array of field objects where element
is the type of field. Currently input, select, checkbox and textarea fields are supported.
interface CustomField {
element: 'input' | 'select' | 'textarea';
type: string;
name: string;
label?: string;
focus?: boolean;
options?: Array<[string, string, OptionHTMLAttributes<any>?]>;
attrs?: InputHTMLAttributes<any> & SelectHTMLAttributes<any>;
}
Note that supplying a customFields
object completely replaces the defaults, so don't forget to add all needed fields. customSchema
should be a Zod schema with matching name attributes.
<ForgotPassword
handler={forgotPasswordHandler}
successMessage={CustomSuccessMessage}
customFields={[
{
element: 'input',
type: 'text',
name: 'email',
label: 'Email',
focus: true,
},
{
element: 'input',
type: 'text',
name: 'secretQuestion1',
label: "What is your mother's maiden name?",
},
{
element: 'input',
type: 'text',
name: 'secretQuestion2',
label: 'What was the name of your first pet?',
},
]}
customSchema={customSchema}
/>
CSS
Basic namespaced (BEM) css can be imported: import '@unleashit/forgot-password/dist/forgot-password.css'
. Alternatively, if you use CSS Modules you can import css from '@unleashit/forgot-password/dist/forgot-password.module.css'
and provide to the cssModule
prop and/or use your own custom module targeting the internal class names. Please see CSS in the main readme of the repo for more info.
Props
ForgotPassword
type BaseFormProps = {
handler: <T extends ZodTypeAny>(
values: FormValues<T>,
) => Promise<ServerResponse<FormValues<T>>>;
onSuccess?: <T extends ZodTypeAny, Meta extends Record<string, any>>(
resp: ServerResponse<FormValues<T>, Meta>,
) => void;
title?: string;
header?: React.FC<DefaultHeaderProps> | false | null;
footer?: React.FC<any>;
loader?: React.FC<DefaultLoaderProps>;
customFields?: CustomField[];
customSchema?: z.AnyZodObject | z.ZodEffects<any>;
toast?: (msg: string) => void;
failMsg?: string;
successMessage?: React.FC<any> | string | false | null;
linkComponent?: React.ComponentType<any>;
linkComponentHrefAttr?: string;
cssModule?: Record<string, string>;
};
type ForgotPasswordProps = Omit<BaseFormProps, 'header'> & {
header?: React.FC<DefaultForgotPasswordHeaderProps> | false | null;
signupUrl?: string;
childrenPosition?: 'top' | 'bottom';
loginLink?: string | false | null;
loginLinkText?: string;
children?: React.ReactNode;
};
ForgotPasswordReset
ForgetPasswordReset is being refactored and has been temporarily unpublished.