JohnWrensby JohnWrensby - 11 months ago 62
React JSX Question

Getting input values without rerender

I have a text input (for the search text) and a button (to initiate the search). It seems from all the examples, that in order to have the searchtext value available in my search click handler (to trigger an Action), I have to have the input use a state value and update the state when the onChange occurs. This causes rerendering. How can I avoid all the rerenders when the user is just typing chars into the input? I only want the value at the time the search button is pressed.

Answer Source

Simple: implement shouldComponentUpdate for your component:


  • Don't link this.state to your input element's value (<input value={this.state} />), this makes the input an uncontrolled component
  • Instead just give it a ref: <input ref={input => {this.inputElement = input}} />
  • When the submit button is hit just get the input value via the ref:

    const inputValue = this.inputElement.value