Languages
[Edit]
EN

React - form example (uncontrolled class component)

0 points
Created by:
chelsea
806

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

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

With createRef() method 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 (this.usernameRef.curent.value, this.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';

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.usernameRef = React.createRef();
    this.passwordRef = React.createRef();
  }

  handleSubmit = e => {
    e.preventDefault();
    const data = {
      username: this.usernameRef.current.value,
      password: this.passwordRef.current.value
    };
    const json = JSON.stringify(data, null, 4);
    console.clear();
    console.log(json);
  };

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <div>
          <label>Username: </label>
          <input ref={this.usernameRef} type="text" />
        </div>
        <div>
          <label>Password: </label>
          <input ref={this.passwordRef} type="password" />
        </div>
        <button type="submit">Submit</button>
      </form>
    );
  }
};

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. 

Note:
Go to this article to see functional component example. 

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 Forms

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