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 - we use React.useRef hook to create usernameRef and passwordRef that let us to access HTML input elements.

In handleSubmit function we:

  • block page realoding with 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 during working with JSX Compiler.
// 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 );


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.

❤️💻 🙂