How can i create component Input using react-hook-form?

Viewed 117

How can i create component Input using react-hook-form?

This is my Input component. I want to convert it using react-hook-form.I haven't seen examples anywhere on the internet yet.

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>
    );
}
1 Answers

The best solution, in my opinion, is connected it with useFormContext and <FormProvider />, Because of that you can do a lot of things transparently.

Take a look into this example:

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>
  )
}

More about useFormContext you can read in https://react-hook-form.com/api/useformcontext (useFormContext requires )

Related