Table of Contents

About

This page is about the handling of input element in React.

Example

These examples are made with a function components.

If you still want to see the same example with class component, they are here: Examples of React Input Element with Class component

Controlled component

The react forms components input accept a value attribute that is used to implement a controlled component.

A React form:

const NameForm = function(){

  const [name, setName] = React.useState('DEFAULT');


  const handleChange = function(event) {
    // toUppercase to enforce it
    console.log('handleChange was fired with the value '+event.target.value.toUpperCase());
    setName(event.target.value.toUpperCase());
  }

  const handleSubmit = function(event) {
    console.log('Your submitted name is: ' + name);
    event.preventDefault();
  }

  return (
      <div>
      <p>Submit your name. It will be always uppercase and for each keystroke, the value attribute will be updated.</p>
      <form onSubmit={handleSubmit}>
        <label>
          Name:
          <input type="text" value={name} onChange={handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
      </div>
    );

}

ReactDOM.render(
  <NameForm />,
  document.getElementById('root')
);
<div id="root"></div>

Uncontrolled Component

input example with a Uncontrolled Component.

We are using a ref to get the value back as example but you could also use the event to get the value.

Note that in React, you define the default value with the attribute defaultValue and not value.

const NameForm = function() {

  const input = React.useRef();

  const handleChange = function(event) {
    // Always uppercase :)
    console.log('handleChange was fired with the value via the event to '+event.target.value);
    // The ref gives access to the HTML element via current
    console.log('handleChange was fired with the value via the dom ref element '+input.current.value);
  }
  
  const handleSubmit = function(event) {
    console.log('The ref gives access to the HTML element via current. Ref Proto: ' + input.current.__proto__.toString());
    console.log('where you have access to all HTML attribute such as the value');
    console.log('Example: the name submitted was: ' + input.current.value);
    event.preventDefault();
  }


    return (
      <form onSubmit={handleSubmit}>
        <label>
          Name:
          <input type="text" ref={input} defaultValue="ChangeMe"  onChange={handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
    
}

ReactDOM.render(
  <NameForm />,
  document.getElementById('root')
);
<div id="root"></div>