Reputation: 129
In React a have a search bar which shows up after I click "Open" button. Search bar appears smoothly because I use translateX property. Then I would like to use focus() on the input element in this search bar. I tried to use refs. Focus appears but it appears as soon as I press the button and stays all the way the search bar moves from one part of the screen to the other(rememeber, it because I use translateX). So it all rides before my eyes. How to make focus appers after the search bar 'reached the destination' on the screen? I tried
if (props.visibleSearchBar) {
ReactDOM.findDOMNode(inputRef.current).focus()
}
instead of
if (props.visibleSearchBar) {
inputRef.current.focus();
} // same story
const Search = (props) => {
let inputRef = useRef(null);
if (props.visibleSearchBar) {
inputRef.current.focus();
}
return (
<div>
<input ref={inputRef} />
</div >
)
Upvotes: 0
Views: 340
Reputation: 602
You can disable the input initially, and enable it after the transition ends.
something like this, (it is not tested).
const [disabled, setDisabledState] = useState(true)
useEffect(() => {
const callback = () => {
setDisableState(false)
inputRef.current.focus();
}
inputRef.current.addEventListener('transitionend', callback)
return () => inputRef.current.removeEventListener('transitioned', callback)
}, [])
return (
<div>
<input ref={inputRef} disabled={disabled}/>
</div >
)
Upvotes: 1