React - form example (uncontrolled components)

3 points
Created by:

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

Below example shows how to make a form as a functional controlled component.

With React.useRef() we create references that will be used to get DOM input elements access. References are attached via ref properties. In 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 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 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.


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.

❤️💻 🙂