React - form submit

3 points
Created by:

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 => {
        const data = {
            username: usernameRef.current.value,
            password: passwordRef.current.value
        const json = JSON.stringify(data, null, 4);
    return (
        <form onSubmit={handleSubmit}>
            <label>Username: </label>
            <input type="text" ref={usernameRef} />
            <label>Password: </label>
            <input type="password" ref={passwordRef} />
          <button type="submit">Submit</button>

const root = document.querySelector('#root');
ReactDOM.render(<Form />, root );
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.


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.

❤️💻 🙂