React - form example (uncontrolled components)

3 points
Created by:

In this article, we would like to show you how to use React forms.

The below example shows how to use a form as a functional uncontrolled component.

With React.useRef() we create references that will be used to get DOM input elements access. References are attached via ref properties. In the below example, references are attached to username and password inputs. When onSubmit event occurs then usernameRef and passwordRef are used to create data object (usernameRef.curent.value, passwordRef.current.value). That data object can be later sent to some server or used to do some other operations - in our case we just print JSON in the console.

Practical example:

// 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 ref={usernameRef} type="text" />
          <label>Password: </label>
          <input ref={passwordRef} type="password" />
        <button type="submit">Submit</button>

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

Note: above solution is quite good but there are better ways how to manage forms with big amount of fields inside form.

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 example (uncontrolled components)
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.

❤️💻 🙂