focus change in react js code example

Example 1: react focus textarea

const focusDiv = useRef();

useEffect(() => {
 if(focusDiv.current) focusDiv.current.focus(); 
}, [focusDiv]);

return (
  <div ref={focusDiv}></div>
);

Example 2: react focus

const FocusDemo = () => {

    const [inputRef, setInputFocus] = useFocus()

    return (
        <> 
            <button onClick={setInputFocus} >
               FOCUS
            </button>
            <input ref={inputRef} />
        </>
    )

}

const useFocus = () => {
    const htmlElRef = useRef(null)
    const setFocus = () => {htmlElRef.current &&  htmlElRef.current.focus()}

    return [ htmlElRef, setFocus ] 
}

Tags:

Html Example