TanStackT
TanStack14mo ago
10 replies
verbal-lime

DeepKeys, only keys with a string value

Hi, I'm trying to make a reusable component that may receive a key into formdata but I want to constrain the component to only receive paths to string values. How can I achieve this? Right now I only have name set to DeepKeys<TFormData> which I guess is too broad.

import type { DeepKeys, ReactFormApi } from "@tanstack/react-form";
import type { ZodValidator } from "@tanstack/zod-form-adapter";
import { useId } from "react";
import { z } from "zod";
import { Input } from "./components/Input";
import { Label } from "./components/Label";

export const PasswordField = <TFormData,>({
    form,
    validatorKey,
    name,
}: {
    form: ReactFormApi<TFormData, ZodValidator>;
    name: DeepKeys<TFormData>;
    validatorKey: "onChange" | "onSubmit";
}) => {
    const field = form.useField({
        name: name,
        validators: {
            [validatorKey]: z
                .string()
                .min(8, "Password needs to have at least 8 characters."),
        },
    });

    const fieldId = useId();

    return (
        <div className="mb-5">
            <Label htmlFor={fieldId} className="mb-1">
                Password
            </Label>
            <Input
                id={fieldId}
                type="password"
                value={field.state.value}
                onBlur={field.handleBlur}
                onChange={(e) => field.handleChange(e.target.value)}
                className="mb-1"
                aria-invalid={field.state.meta.errors.length > 0}
            />
            {field.state.meta.errors.length > 0 && (
                <div className="text-red-500 font-medium py-1">
                    {field.state.meta.errors[0]}
                </div>
            )}
        </div>
    );
};
Was this page helpful?