Imp3ll
Imp3ll

Reputation: 41

How leave from infinite rerender?

When blur, I want the blurEvent function to be executed, it is executed but then goes into an infinite loop because of inputRef.current.blur ();. But I need to somehow get out of the input focus. How can this problem be solved?

const inputRef = React.useRef(null);
const blurEvent= () => {
  inputRef.current.focus({
    cursor: 'start',
  })
     inputRef.current.blur();
}
<Input
  placeholder="Name"
  required
  ref={inputRef}
  onBlur={blurEvent}
/>

with useState()

const [isFocused, setIsFocused] = useState(false)
const inputRef = React.useRef(null)
const handleOnBlur = () => {
  if (isFocused) {
    inputRef.current.focus({
      cursor: 'start',
    })
    inputRef.current.blur()
  }
  setIsFocused(false)
}
<Input
  placeholder="Name"
  required
  ref={inputRef}
  onFocus={() => setIsFocused(true)}
  onBlur={blurEvent}
/>

Upvotes: 0

Views: 217

Answers (1)

Shakya Peiris
Shakya Peiris

Reputation: 612

You can give that task to two event functions with a boolean as follows.

const inputRef = React.useRef(null);
const [isAutoFocused,setIsAutoFocused] = useState(false)
const blurEvent= () => {
  inputRef.current.focus({
    cursor: 'start',
  })
  setIsAutoFocused(true)
}
const focusEvent = () => {
    if (!isAutoFocused){
        return
    }
    inputRef.current.blur();
    setIsAutoFocused(false)
}
<Input
  placeholder="Name"
  required
  ref={inputRef}
  onBlur={blurEvent}
  onFocus={focusEvent}
/>

Upvotes: 1

Related Questions