Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lunaperegrina/fd8020d8dff963232b678a0f68febb8d to your computer and use it in GitHub Desktop.
Save lunaperegrina/fd8020d8dff963232b678a0f68febb8d to your computer and use it in GitHub Desktop.
Input of BRL with shadn/ui and react-hook-form with placeholder and currency
<FormField
control={form.control}
name="price"
render={({ field }) => (
<FormItem>
<FormLabel>Preço</FormLabel>
<FormControl>
<Input
type="text" // Changed from "number" to "text" for better currency formatting
placeholder="R$ 10,00"
{...field}
value={field.value ?
(field.value / 100).toLocaleString("pt-BR", {
style: "currency",
currency: "BRL",
}) :
""
}
onChange={(e) => {
const rawValue = e.target.value.replace(/\D/g, '');
const valueInCents = rawValue ? parseInt(rawValue) : 0;
field.onChange(valueInCents);
}}
onBlur={() => {
// Ensure proper formatting when leaving the field
if (field.value) {
field.onChange(field.value);
}
}}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment