'Focus TextInput after select

I got an error when I tried to focus a TextInput after selecting a Dropdown value. And also, when I tried to write, it's lost focus, but I think it is related to how I'm trying to do this.

This is the function that I use to set the inputRef

  let inputRef = useRef<TextInput | null>(null)

  const onSelectFormat = (format) => {
    setDropdownListVisibility('')
    setInputFocused(true)
    inputRef.current &&  inputRef.current.focus()
  }

The CustomInput Component that I send the inputRef variable

      <CustomInput
        value={value}
        onChangeText={onChangeInputText}
        isFocused={isInputFocused}
        onFocus={() => setInputFocused(true)}
        getRef={ref => (inputRef = { current: ref })}
      />

And finally, this is the child component that I pass the ref.

        <TextInput
          ref={getRef}
          value={value}
          onChangeText={onChangeText}
          style={styles.input}
          onFocus={onFocus}
        />


Solution 1:[1]

Your code appears to be partially set up for call-back refs, and partially for regular refs, (created with useRef or createRef). If you create the ref with useRef, just can just pass it all the way down to the element where it is used, without using any functions or assignments (and it can also be a constant).

The code should work if you replace getRef={ref => (inputRef = { current: ref })} in the CustomInput element with getRef={inputRef}, but it will be cleaner if you also use the prop name inputRef instead of getRef:

..
const inputRef = useRef<TextInput | null>(null)

const onSelectFormat = (format) => {
  setDropdownListVisibility('')
  setInputFocused(true)
  inputRef.current?.focus()
}
..
  ..
  <CustomInput
    value={value}
    onChangeText={onChangeInputText}
    isFocused={isInputFocused}
    onFocus={() => setInputFocused(true)}
    inputRef={inputRef}
  />
  ..
  ..
  <TextInput
    ref={inputRef}
    value={value}
    onChangeText={onChangeText}
    style={styles.input}
    onFocus={onFocus}
  />
  ..

(with the function definition for CustomInput also adapted to the new inputRef prop name)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Oblosys