-- Main.shssdhakchina - 02 Feb 2022

React Forms in Class Components

If we understand the forms in functional components, it is very easy to understand the concepts behind the Forms in Class Components. Instead of using hooks, we are going to directly manage the state values in the class methods. This is the only difference in class components. Please take a close look at the example codes below to understand the difference.

Uncontrolled Component

In the below code, the state is not managed. Hence this is called uncontrolled DOM managed form.

import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component {
   
   onInputChange(event) {
      console.log(event.target.value);
   }
   
   render() {
      return (
         <div>
            <form>
               <label>Enter text</label>
               <input type="text"
                  onChange={this.onInputChange}/>
            </form>
         </div>
      );
   }
}

ReactDOM.render(<App />,
         document.querySelector('#root'));

State Managed Form Component

Observe the below sample how the state is managed as and when the user keys in.
import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component {
   
   state = { inputValue: '' };
   
   render() {
      return (
      <div>
         <form>
            <label> Enter text </label>
            <input type="text"
               value={this.state.inputValue}
               onChange={(e) => this.setState(
               { inputValue: e.target.value })}/>
         </form>
         <br/>
         <div>
            Entered Value: {this.state.inputValue}
         </div>
      </div>
      );
   }
}

ReactDOM.render(<App />,
         document.querySelector('#root'));

Managing Form Submission

Observe the below sample how the form submission is handled and also how the default form submit is avoided.

import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component {
   
   state = { inputValue: '' };

   onFormSubmit = (event) => {
      event.preventDefault();
      this.setState({ inputValue: 'Hello World!'});
   }
   
   render() {
   
      return (
      <div>
         <form onSubmit={this.onFormSubmit}>
            <label> Enter text </label>
            <input type="text"
            value={this.state.inputValue}
            onChange={(e) => this.setState(
            { inputValue: e.target.value })}/>
         </form>
         <br/>
         <div>
            Entered Value: {this.state.inputValue}
         </div>
      </div>
      );
   }
}

ReactDOM.render(<App />,
      document.querySelector('#root'));

Topic revision: r1 - 02 Feb 2022, shss\dhakchina
This site is powered by FoswikiCopyright © by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding Foswiki? Send feedback