react hook form typescript

Solutions on MaxInterview for react hook form typescript by the best coders in the world

showing results for - "react hook form typescript"
Ignacio
09 Mar 2017
1import React from 'react';
2import { useForm } from 'react-hook-form';
3import "./App.css";
4
5type Profile = {
6  firstname: string
7  lastname: string
8  age: number
9}
10
11function App() {
12  const {register, handleSubmit, errors} = useForm<Profile>()
13
14  const onSubmit = handleSubmit((data) => {
15    alert(JSON.stringify(data))
16  })
17
18  return (
19    <main>
20    <form onSubmit={onSubmit}>
21      <div>
22        <label htmlFor="firstname">First Name</label>
23        <input ref={register({ required: true })} id="firstname" name="firstname" type="text"/>
24        {
25          errors.firstname && <div className="error">Enter your name</div>
26        }
27      </div>
28      <div>
29        <label htmlFor="lastname">Last Name</label>
30        <input ref={register({ required: true })} id="lastname" name="lastname" type="text"/>
31        {
32          errors.lastname && <div className="error">Enter your last name</div>
33        }
34      </div>
35      <div>
36        <label htmlFor="age">Age</label>
37        <input ref={register({ required: true })} id="age" name="age" type="text"/>
38        {
39          errors.age && <div className="error">Enter your age</div>
40        }
41      </div>
42      <button type="submit">Save</button>
43    </form>
44    </main>
45  );
46}
47
48export default App;