react-hook-form typescript code example

Example 1: react-hook-form typescript

import React from 'react';
import { useForm } from 'react-hook-form';
import "./App.css";

type Profile = {
  firstname: string
  lastname: string
  age: number
}

function App() {
  const {register, handleSubmit, errors} = useForm<Profile>()

  const onSubmit = handleSubmit((data) => {
    alert(JSON.stringify(data))
  })

  return (
    <main>
    <form onSubmit={onSubmit}>
      <div>
        <label htmlFor="firstname">First Name</label>
        <input ref={register({ required: true })} id="firstname" name="firstname" type="text"/>
        {
          errors.firstname && <div className="error">Enter your name</div>
        }
      </div>
      <div>
        <label htmlFor="lastname">Last Name</label>
        <input ref={register({ required: true })} id="lastname" name="lastname" type="text"/>
        {
          errors.lastname && <div className="error">Enter your last name</div>
        }
      </div>
      <div>
        <label htmlFor="age">Age</label>
        <input ref={register({ required: true })} id="age" name="age" type="text"/>
        {
          errors.age && <div className="error">Enter your age</div>
        }
      </div>
      <button type="submit">Save</button>
    </form>
    </main>
  );
}

export default App;

Example 2: install react hook form

npm install react-hook-form

Example 3: react hooks form

import React from 'react';
import { useForm } from 'react-hook-form';

function App() {
  const { register, handleSubmit, errors } = useForm(); // initialize the hook
  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input name="firstname" ref={register} /> {/* register an input */}
      <input name="lastname" ref={register({ required: true })} />
      {errors.lastname && 'Last name is required.'}
      <input name="age" ref={register({ pattern: /\d+/ })} />
      {errors.age && 'Please enter number for age.'}
      <input type="submit" />
    </form>
  );
}

Example 4: react select with react hook form cotroller

function Yourcomponent(props){

    const methods = useForm();
    const { handleSubmit } = methods;
    

    const options = [
     { value: '1', label: 'Apple'},
     { value: '2', label: 'Ball'},
     { value: '3', label: 'Cat'},
    ];
    
    const default_value = 1; // you can replace with your default value
    

    // other codes of the component 
    

    function submitHandler(formData){
    
    // values are available in formData

    }


    return(
      <div>
        
        {* other part of your component *}
        <form onSubmit={handleSubmit(submitHandler)} >

           {* other part of your form *}
            <Controller
                control={methods.control}
                defaultValue={default_value}
                name="field_name_product"
                render={({ onChange, value, name, ref }) => (
                    <Select
                        inputRef={ref}
                        classNamePrefix="addl-class"
                        options={options}
                        value={options.find(c => c.value === value)}
                        onChange={val => onChange(val.value)}
                    />
                )}
            />

           {* other part of your form *}
        </form>

        {* other part of your component *}
      </div>
    )
}

Tags: