Categories
React Answers

How to Get Form Data in React?

Spread the love

Sometimes, we want to get form data from form fields in React.

In this article, we’ll look at how to get form data from form fields in React.

Get Form Data in React

To get form data from form fields in React, we can store the input values in states and then get the values when we need them.

For instance, we can write:

import React, { useState } from "react";

export default function App() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const handleEmailChange = (e) => {
    setEmail(e.target.value);
  };

  const handlePasswordChange = (e) => {
    setPassword(e.target.value);
  };

  const handleLogin = () => {
    console.log(email, password);
  };

  return (
    <form>
      <input
        type="text"
        name="email"
        placeholder="Email"
        value={email}
        onChange={handleEmailChange}
      />
      <input
        type="password"
        name="password"
        placeholder="Password"
        value={password}
        onChange={handlePasswordChange}
      />
      <button type="button" onClick={handleLogin}>
        Login
      </button>
    </form>
  );
}

We defined the email and password states with the useState hooks.

Then we defined the handleEmailChange and handlePasswordChange functions that calls setEmail and setPassword with e.target.value to set the email and password states respectively.

e.target.value has the inputted values from the input fields.

Next, we add 2 input fields that have the value and onChange props set.

value is set to the states that have the input values.

onChange is set to change event handler functions that’s used to set the email and password states to the inputted values.

Then we add a button with the onClick prop sets to the handleLogin function that logs the email and password values that are typed in before clicking the button.

Conclusion

To get form data from form fields in React, we can store the input values in states and then get the values when we need them.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *