Uncontrolled Component in React.js

React JSJavascript LibraryFront End Technology

In controlled component form data is handled by React component by writing event handler for state updates. But in uncontrolled component, form data is handled by DOM itself.

ref is used to receive the form value from DOM.

Example

class UserNameForm extends React.Component {
   constructor(props) {
      super(props);
      this.handleFormSubmit = this.handleFormSubmit.bind(this);
      this.inputUserName = React.createRef();
   }
   handleFormSubmit(event) {
      console.log('username: ' + this.inputUserName.current.value);
      event.preventDefault();
   }
   render() {
      return (
         <form onSubmit={this.handleFormSubmit}>
            <label>
               Name:
               <input type="text" ref={this.inputUserName} />
            </label>
            <input type="submit" value="Submit" />
         </form>
      );
   }
}

Reacts createRef function creates areference for form field and on form submission we can access the field value suing this.inputUserName.current .value. Notice the use of current after ref name.

It’s a quick and dirty solution with less code actually but with less control.

With uncontrolled component React provided an attribute called as defaultValue to give the initial value to form field.

render() {
   return (
      <form onSubmit={this.handleFormSubmit}>
         <label>
            User Name:
            <input
               defaultValue="Steve"
               type="text"
               ref={this.inputUserName} />
         </label>
         <input type="submit" value="Submit" />
      </form>
   );
}

The input type file is always an uncontrolled component because its value can be set by user only and not by programmatically.

Example

Example of file input −

class FileInputExample extends React.Component {
   constructor(props) {
      super(props);
      this.handleFormSubmit = this.handleFormSubmit.bind(this);
      this.selectedFileInput = React.createRef();
   }
   handleFormSubmit(event) {
      event.preventDefault();
      console.log(
         `Selected file - ${
            this.selectedFileInput.current.files[0].name
         }`
      );
   }
   render() {
      return (
         <form onSubmit={this.handleFormSubmit}>
            <label>
               Upload file:
               <input type="file" ref={this.selectedFileInput } />
            </label>
            <br />
            <button type="submit">Submit</button>
         </form>
      );
   }
}
ReactDOM.render(
   <FileInputExample />,
   document.getElementById('root')
);
raja
Published on 28-Aug-2019 12:22:15
Advertisements