
React Hooks are a powerful tool when it comes to managing state in React components. They allow us to create reusable logic that can be easily shared across multiple components, making them incredibly useful for manipulating the data within form components.
In this article, we’ll cover the basics of React Hooks and how to use the setValue hook in a form component. We’ll look at how to pass values into the hook as well as how to use callback functions for updating elements on the page.
Here’s one working example of a ReactJS app using useState
hook to set values in a form
component.
import React, { useState } from "react";
import { useForm } from "react-hook-form";
function App() {
const [formData, setFormData] = useState({
name: "",
lastname: "",
email: "",
});
const { register, handleSubmit, setValue } = useForm();
const onSubmit = (data) => {
// send to server
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
{" "}
<input
type="text"
name="name"
ref={register}
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
/>{" "}
<input
type="text"
name="lastname"
ref={register}
value={formData.lastname}
onChange={(e) => setFormData({ ...formData, lastname: e.target.value })}
/>{" "}
<input
type="text"
name="email"
ref={register}
value={formData.email}
onChange={(e) => setFormData({ ...formData, email: e.target.value })}
/>{" "}
<input type="submit" />{" "}
</form>
);
}
export default App;
The code above uses the useForm
hook to set up a form, in addition to using React’s useState hook. The useForm hook provides the register
, handleSubmit
, and setValue
methods, which the code uses to handle form data.
The code sets up an onChange
handler for each form field, which updates the formData
state with the current field value.
The register
ref is then used to register each form field, which associates the field with the form’s data. Finally, setValue
is used to set the initial value of the form fields to the values stored in the formData
state.
Lastly we are setting up an onSubmit
handler that logs the form data when the form is submitted. Of course, in a real app, you would do something useful in this function like sending the formData
to a backend.
Leave a Reply