1 | initial version |
To detect changes made to an input value using buttons in React/Typescript with React-hook-form, you can use the watch
method from the hook. Here is an example of how this can be implemented:
import React from "react";
import { useForm } from "react-hook-form";
type FormData = {
inputOne: string;
inputTwo: string;
};
const ExampleForm: React.FC = () => {
const { register, watch, handleSubmit } = useForm<FormData>();
// Watch for changes in inputOne
const inputOne = watch("inputOne");
// Handle form submit
const onSubmit = (data: FormData) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<label htmlFor="inputOne">Input One</label>
<input id="inputOne" name="inputOne" ref={register} />
<label htmlFor="inputTwo">Input Two</label>
<input id="inputTwo" name="inputTwo" ref={register} />
<button type="button" onClick={() => console.log(inputOne)}>
Log Input One
</button>
<button type="submit">Submit</button>
</form>
);
};
export default ExampleForm;
In this example, we first define the shape of our form data using the FormData
type. We then use the useForm
hook to initialize our form with register
for each input field. We also use the watch
method to listen for changes in inputOne
.
We then define our onSubmit
function to handle form submissions.
Finally, we render our inputs, along with two buttons. The first button logs the current value of inputOne
when clicked, and the second button is used to submit the form.
By using the watch
method, we're able to easily detect changes made to our input values using buttons in React/Typescript with React-hook-form.