Categories
JavaScript React

React – How to Get Form Values on Submit

Spread the love

To get form values on submit, we can pass in an event handler function into the onSubmit prop to get the inputted form values.

To do that, we write:

import React from "react";

export default function App() {
  const [name, setName] = React.useState("");
  const handleSubmit = e => {
    e.preventDefault();
    console.log(name);
  };
  return (
    <div className="App">
      <form onSubmit={handleSubmit}>
        <input
          typ="text"
          value={name}
          onChange={e => setName(e.target.value)}
        />
        <br />
        <input type="submit" />
      </form>
    </div>
  );
}

We use the useState hook so that we can use the phone state as the value of the value prop.

The onChange prop has a function that calls setName returned by the useState prop to set the value of name with it.

Then we can enter something and see what we entered.

Then we defined the handleSubmit function, which takes an event object e as a parameter.

We’ve to call e.preventDefault to prevent the default server-side submit behavior.

Then we log the value of name to show the value of it in the console.

Now when we enter something and press the Submit button, we’ll see the value of what we entered logged in the console.

With React, getting form values on submit isn’t hard to do. We just have to pass an event handler function to the onSubmit that takes an event object parameter.

Then inside it, we call preventDefault and then we can get the inputted form field data from the state as long as we set the inputted value to a state variable with the onChange handler.

Leave a Reply

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