React text form fields without onChange

Viewed 6889

Is there any way (please provide an example) in React / React Native to have a component render a timer with milliseconds, a submit button, and a text input field where the following conditions are met?

  1. The user can type in the input field and see what he is typing.
  2. No event handlers are assigned to the input field
  3. When the submit button is clicked the program displays an alert() with the text typed by the user.
  4. The component has an initial state value that is initially displayed in the input field.
  5. The user does not experience unexpected behaviors while typing.

A previous question about this subject lead me to this more specific question about the matter (I hope you can see how it is related).

The most commonly accepted pattern in React to implement input fields suggest to always use an onChange event (see the docs), but I think this leads to repetition and noise in the code, so I´m looking for a better pattern where the developer doesn´t have to think about the onChange behavior when all he needs is an input form field.

Extra Note 1: An "state value" is a value in the component's state. i.e. "constructor(){ this.state = {value:'Initial Value'} };".

Extra Note 2: The purpose of the timer is to make sure you're triggering a render() periodically, which makes it a challenge to display the initial "state value", and allow the user to type normally without an onChange handler to update the state accordingly.

2 Answers

Your conditions will be met with this refs-based pattern ?

class App extends React.Component {
  constructor(props) {
    super(props);
    this.textInput = null;
  }
  
  handleSubmit = () => alert(this.textInput.getDOMNode().value);
  render() {
    return (
      <div>
        <textarea 
          ref={el => this.textInput = el}
        >
          My initial value
        </textarea>
        <button onClick={this.handleSubmit}type="button">Submit</button>
      </div>
    );
  }
  
}

React.render(<App />, document.getElementById('app'));
<div id="app"></div>

Working codepen: https://codepen.io/anon/pen/roypOx

Because conditions are about only input field and not timers I've not included a timer in the example.

Related