Languages
[Edit]
EN

React - form submit

3 points
Created by:
p_agon
589

In this article we would like to show you how to submit a form in React.

In below example we access form fields with references by React.useRef() hook to create usernameRef and passwordRef that let us to access HTML input elements.

In handleSubmit function we:

  • block page realoding using preventDefault() method,
  • use the references to get field values and create data object that is converted to JSON and displayed in console - we can send that JSON with AJAX to backend too.

handleSubmit  function is attached to onSubmit event property that is fired when submit action occurs - when Submit button is clicked.

// ONLINE-RUNNER:browser;

// Note: uncomment import lines in your project.
// import React from 'react';
// import ReactDOM from 'react-dom';

const Form = () => {
    const usernameRef = React.useRef();
    const passwordRef = React.useRef();
    const handleSubmit = e => {
        e.preventDefault();
        const data = {
            username: usernameRef.current.value,
            password: passwordRef.current.value
        };
        const json = JSON.stringify(data, null, 4);
        console.clear();
        console.log(json);
    };
    return (
        <form onSubmit={handleSubmit}>
          <div>
            <label>Username: </label>
            <input type="text" ref={usernameRef} />
          </div>
          <div>
            <label>Password: </label>
            <input type="password" ref={passwordRef} />
          </div>
          <button type="submit">Submit</button>
        </form>
    );
};

const root = document.querySelector('#root');
ReactDOM.render(<Form />, root );

 

See also

  1. React - optimal way to create and submit form data 
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - form submit
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join