React useForm Hook

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will be learning how to use the useForm hook in React to create a stateful value from the fields in a form. This will allow us to easily manage the state of our form inputs and update them as needed. By the end of this lab, you will have a better understanding of how to create and manage forms in React using the useForm hook.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/event_handling("`Handling Events`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") subgraph Lab Skills react/jsx -.-> lab-38385{{"`React useForm Hook`"}} react/event_handling -.-> lab-38385{{"`React useForm Hook`"}} react/hooks -.-> lab-38385{{"`React useForm Hook`"}} react/use_state_reducer -.-> lab-38385{{"`React useForm Hook`"}} end

React useForm Hook

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

To create a stateful value from the fields in a form, you can use the useState() hook to create a state variable for the values in the form. Then, create a function that updates the state variable based on the appropriate event triggered by a form field.

Here's an example implementation:

const useForm = (initialValues) => {
  const [values, setValues] = React.useState(initialValues);

  return [
    values,
    (e) => {
      setValues({
        ...values,
        [e.target.name]: e.target.value
      });
    }
  ];
};

In the example above, useForm() takes an initial state object, creates a state variable values using useState(), and returns an array with values and a function that updates values based on the event passed to it.

You can use useForm() in a form component like this:

const Form = () => {
  const initialState = { email: "", password: "" };
  const [values, setValues] = useForm(initialState);

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(values);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="email" name="email" onChange={setValues} />
      <input type="password" name="password" onChange={setValues} />
      <button type="submit">Submit</button>
    </form>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<Form />);

In the Form component, useForm() is called with an initial state object and returns an array with values and setValues(). The handleSubmit() function logs the values object to the console when the form is submitted. The input elements are set up to update the form values using the setValues() function.

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the React useForm Hook lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like