Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React and text inputs - use onBlur or onChange?

I am working on a form with about 6 text input fields.

To save the values to my state, is it better to do so onBlur or onChange?

For example with onChange,

onChangeTextInput = ({ name, value }) => {
    this.setState(state => ({
      ...state,
      form: {
        ...state.form,
        [name]: value
      }
    }));
  };

Each time a key is pressed it will update the state. When I use the react tools "show update" I see a ton of updates because of how many times the field is updated.

Should I use onBlur instead to avoid this? Or is there a way to "batch" the state update?

Thanks

like image 222
a person Avatar asked Sep 26 '18 02:09

a person


1 Answers

So it depends what you want the scenario to be :)

OnBlur will only trigger once the user clicks out of the field, if that isn't the correct user experience for you, my suggestion would be to use an input delay (also known as debouncing)! very cool once you get it dialed in nicely.

I won't give you the code outright because it's a really useful tool to understand properly in the future but check out:

import {debounce} from 'throttle-debounce';

There are many packages like this once, but what it does is set's a timeout on a function in your constructor:

this._updateValues = debounce(500, this._updateValues);

Every time this function is called it will wait 500 milliseconds before running, but if it is called again within that time frame, the timer will be reset :)

like image 89
Tom Rowe Avatar answered Oct 08 '22 23:10

Tom Rowe