1import React from 'react';import { useForm } from 'react-hook-form'; function App() { const { register, handleSubmit, errors } = useForm(); // initialise 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> );}
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;
1import React, { useState } from 'react';
2function Example() {
3 // Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0);
4 return (
5 <div>
6 <p>You clicked {count} times</p>
7 <button onClick={() => setCount(count + 1)}>
8 Click me
9 </button>
10 </div>
11 );
12}