ui icon indicating copy to clipboard operation
ui copied to clipboard

Create a custom Input component with value formatter

Open martinmorenoc opened this issue 1 year ago • 0 comments

I am trying to implement a custom CustomInput for a form guiding me in the shadcn input component standard. Basically I want that when a user types, a formatting function is applied to the text, but when the form is submitted, the CustomInput returns the value without the formatting function applied.

Right now I have something like this, which is formatting the value on change, but is returning also the value formatted.

const CustomInput = React.forwardRef<HTMLInputElement, RutInputProps>(
  ({ className, ...props }, ref) => {
    return (
      <input
        ref={ref}
        {...props}
        onChange={(e) => {
          e.target.value = formatValue(e.target.value)
          props.onChange?.(e)
        }}
        value={props.value as string}
        className={cn(
          'flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
          className,
        )}
      />
    )
  },
)

martinmorenoc avatar Oct 02 '23 17:10 martinmorenoc