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.
fixed this by adding timeout like this
useImperativeHandle(ref, () => ({
focusInput: () => {
setTimeout(()=>{
focusableElements[0].value = '1'
focusableElements[0].focus()
},100)
},
}))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With