Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to focus input in react

I'm trying to focus an input box that is inside an Antd tab whenever the user clicks this tab (i.e., whenever the input box is visible). I'm using the useImperativeHandle hook to achieve this.

parent component


const Parent=()=>{
const threadRef=useRef()
() => {
  const onTabChange = activeKey => {
    if (activeKey === 1 && chatThreadRef.current) {
      chatThreadRef.current.focusInput()
    }
  }
  return (
    <Tabs
      items={[
        { label: 'tab 1', key: 0, children: <>tab 1</> },
        { label: 'tab 2', key: 1, children: <ChildComponent/> },
      ]}
      onChange={onTabChange}
    />
  )
}
}

Child component

const ChildComponent = forwardRed((props,ref) => {
  const [focusableElements, setFocusableElements] = useState([])
  const wrapperRef = useRef(null)
  useEffect(() => {
    const messageInput = wrapperRef.current.querySelector('input')
    setFocusableElements(messageInput)
  }, [])

  useImperativeHandle(ref, () => ({
    focusInput: () => {
      console.log(focusableElements[0])
      focusableElements[0].value = '1'
      focusableElements[0].focus()
    },
  }))
  return (
    <div ref={wrapperRef}>
      <Input className="input" />
    </div>
  )
})

Whenever the focusInput is called the in the parent component console.log(focusableElements[0]) statement in the code prints the input element and i'm also able to set the value to the input but its not getting focussed.

like image 619
Vignesh s Avatar asked Sep 15 '25 22:09

Vignesh s


1 Answers

fixed this by adding timeout like this

  useImperativeHandle(ref, () => ({
    focusInput: () => {
      setTimeout(()=>{
      focusableElements[0].value = '1'
      focusableElements[0].focus()
    },100)
    },
  }))
like image 115
Vignesh s Avatar answered Sep 18 '25 16:09

Vignesh s