Password Input
An input that can toggle visibility of the password text.
import { PasswordInput } from "@/components/ui/password-input"
export function BasicPasswordInput() { return <PasswordInput defaultValue="Password" className="w-[250px]" />}
Installation
Section titled “Installation”Copy and paste the following code into your project.
components/ui/password-input.tsx
"use client"
import { Button } from "@/components/ui/button"import { Input } from "@/components/ui/input"import { cn } from "@/lib/utils"import { EyeIcon, EyeOffIcon } from "lucide-react"import { useState, type ComponentProps } from "react"
export function PasswordInput({ className, ...props}: Omit<ComponentProps<typeof Input>, "type">) { const [showPassword, setShowPassword] = useState(false) const Icon = showPassword ? EyeOffIcon : EyeIcon
return ( <div className="relative"> <Input {...props} type={showPassword ? "text" : "password"} className={cn("pr-9", className)} /> <Button variant="ghost" size="icon" type="button" className="absolute inset-y-1/2 right-1 size-7 -translate-y-1/2" onClick={() => setShowPassword(p => !p)} > <Icon className="size-5" /> <span className="sr-only"> {showPassword ? "Hide password" : "Show password"} </span> </Button> </div> )}
Update the import paths to match your project setup.
import { useState } from "react"import { PasswordInput } from "@/components/ui/PasswordInput"
<PasswordInput />
Examples
Section titled “Examples”"use client"
import { zodResolver } from "@hookform/resolvers/zod"import { useForm } from "react-hook-form"import { toast } from "sonner"import { z } from "zod"import { Button } from "@/components/ui/button"import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage,} from "@/components/ui/form"import { PasswordInput } from "@/components/ui/password-input"
const formSchema = z.object({ password: z.string().min(8, "Password must be at least 8 characters long"),})
export function PasswordInputForm() { const form = useForm<z.infer<typeof formSchema>>({ resolver: zodResolver(formSchema), defaultValues: { password: "", }, })
function onSubmit(data: z.infer<typeof formSchema>) { toast("You submitted the following values", { description: ( <pre className="mt-2 w-[320px] rounded-md bg-neutral-950 p-4"> <code className="text-white">{JSON.stringify(data, null, 2)}</code> </pre> ), }) }
return ( <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)} className="w-2/3 space-y-6"> <FormField control={form.control} name="password" render={({ field }) => ( <FormItem> <FormLabel>Password</FormLabel> <FormControl> <PasswordInput {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <Button type="submit">Submit</Button> </form> </Form> )}