Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Material UI onFocusOut

I currently use

<TextField onChange={e => this.change(e, items)}

This gets fired at every single letter I put into the TextField, consequently, text I type gets filled in slow motion. I was thinking it'd be better if this request goes out once the user types everything and focuses away. What kind of event I can use in this scenario with React & Material UI TextField ?

like image 937
Extelliqent Avatar asked Dec 24 '22 01:12

Extelliqent


1 Answers

Having a debounced version of your function is useful when any DOM event is attached. It reduces the number of calls to this function to the bare minimum and thereby improve the performance.

So, you can do this:

import _ from 'lodash';

constructor(props) {
    super(props)

    this.onChangeDebounce = _.debounce(e => this.change(e, items), 300);
}

render() {
    ...
    onChange={e => this.onChangeDebounce(e)}
    ...
}

In this case, I am passing to debounce only two parameters:

  1. The function to be rate-limited
  2. The rate limit in milliseconds, ie., the time to wait before the function is fired.

Or you can use onBlur event, that is available for any DOM element. The onBlur event happens whenever an input loses focus on. In other words: when you remove your cursor from within the input, it loses "focus", or becomes "blurry".

The caveat is that it doesn't have an associated event, so, to reach what you want, you can update the state with the field value and on onBlur, retrieve this value from state.

Here you have a fiddle doing this.

like image 99
Aldo Avatar answered Jan 13 '23 02:01

Aldo