Handling Default Values in Uncontrolled React Elements

working with uncontrolled form elements in React

Handling Default Values in Uncontrolled React Elements

In React, there are instances where you may prefer to have form elements that aren’t tightly controlled. In these cases, setting a starting value is vital, but you’ll also want to let any following modifications be user-driven, without React’s interference. 

To make this happen, rather than using the ‘value’ property, the ‘defaultValue’ attribute is the way to go.

Consider this: when fashioning a text input:

<input defaultValue="John" type="text" ref={this.inputReference} />

This strategy isn’t just confined to text inputs. It’s equally valid for ‘select’ dropdowns and ‘textarea’ boxes. However, when you’re dealing with checkboxes or radio options, you’ll want to lean on ‘defaultChecked’ instead.

One important thing to remember: the default value you set is only stamped onto the component during its first appearance on screen. Should a user decide to input something else, their choice will take precedence over the initially set default.

Code Illustration

Here’s a practical example showing how you can set a starting value for a form field that doesn’t bend to React’s every whim:

import React, { Component } from 'react';

class FreeFormSample extends Component {
  constructor(props) {
    super(props);
    this.inputReference = React.createRef();
  }

  onFormSend = (e) => {
    e.preventDefault();
    alert('User’s Input: ' + this.inputReference.current.value);
  }

  render() {
    return (
      <form onSubmit={this.onFormSend}>
        <label>
          User Name:
          <input
            defaultValue="John" // Putting in the starting value here
            type="text"
            ref={this.inputReference}
          />
        </label>
        <input type="submit" value="Send" />
      </form>
    );
  }
}

export default FreeFormSample;

When users send this form off, they’re greeted with an alert revealing their input. They might stick with the given default, or they could have penned something new. This piece of code is a testament to the power and utility of the ‘defaultValue’ property for setting the starting point for free-willed form fields.

Summing It Up

To keep interactions fluid and user-friendly with React’s uncontrolled components, kick things off with ‘defaultValue’. It’s the key to balancing a helpful starting point with preserving the user’s freedom to choose, all while ensuring a consistent, hassle-free user journey.