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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-05-26 06:19:04 +0000
Seen: 1 times
Last updated: May 26
How can one ensure that sub-classes have uniform method parameters in TypeScript?
Can a TypeScript definition for icon names be provided in MaterialCommunityIcons for React Native?
How can I deal with Expression.Error related to a column in Power Query?
How can you implement pagination in Oracle for the LISTAGG() function?
What is the process for implementing a FutureBuilder on an OnTap function in Flutter?
How can we require users to be logged in before they can access the root folders in WordPress?
In SCSS, what is the method for grouping and reusing a set of classes and styles?