Búsqueda de sitios web

reactjs - ¿Cómo puedo crear un componente Input usando react-hook-form?


¿Cómo puedo crear un componente Input usando react-hook-form?

Este es mi componente Input. Quiero convertirlo usando react-hook-form. Aún no he visto ejemplos en ningún lugar de Internet.

import React, {FC} from "react";
import './input.css'

interface IInputProps {
    type?: string
    placeholder?: string;
    width?: string | number;
    height?: string | number;
    label: string;
    error?: string;
    setValue?: any;
    value?: any;
    name?: string;
}

export const Input : FC<IInputProps> = (
    {
        type = "text",
        placeholder,
        width,
        height,
        label,
        error,
        setValue,
        value,
    }) => {

    return (
        <div className="Input">
            {label ? <label>{label}</label> : null}
            <div>
                <input
                    type={type}
                    placeholder={placeholder}
                    style={{width: width, height: height}}
                    onChange={(e) => setValue(e.currentTarget.value)}
                    value={value}
                />

            </div>
            {error ? <span>{error}</span> : null}
        </div>
    );
}

Respuesta #1

La mejor solución, en mi opinión, es conectarlo con useFormContext y <FormProvider />, debido a eso puedes hacer muchas cosas de manera transparente.

Echa un vistazo a este ejemplo:

import * as React from 'react'
import { Form, FormCheckProps } from 'react-bootstrap'
import * as clsx from 'clsx'
import { useFormContext } from 'react-hook-form'

interface Props extends FormCheckProps {
  wrapperClassName?: string
  name: string
}

export const CircleOutlineRadioButton = ({ name, wrapperClassName, ...props }: Props): React.ReactElement => {
  const { register } = useFormContext()

  return (
    <div className={clsx('position-relative', wrapperClassName)}>
      <div className="position-relative cursor-pointer">
        <Form.Check
          {...props}
          {...register(name)}
          type="radio"
          className={clsx('circle-outline-radio-button', props.className)}
        />
        <i className="uil-check circle-outline-radio-button__check-icon" />
      </div>
    </div>
  )
}

Más sobre useFormContext puedes leer en https://react-hook-form.com/api/useformcontext (useFormContext requiere)