I have a very basic form where I am attempting to control the focus and blur of an input element using state and useEffect. Selecting and deselecting the input via mouse works just fine, but I also have a button that should toggle the focus on/off which is not working properly. When you press the button, the focus never toggles off for some reason.
I must be missing something simple here, but this is driving me crazy. Here is the code below, and a link to a working codepen.
const Focus = () => {
const [focused, setFocused] = useState(true)
const inputRef = useRef()
useEffect(() => {
if (focused) {
inputRef.current.focus()
} else {
inputRef.current.blur()
}
}, [focused])
return (
<div>
<input
ref={inputRef}
type="text"
onBlur={() => setFocused(false)}
onFocus={() => setFocused(true)}
/>
<button onClick={() => setFocused(!focused)}>Toggle Focus</button>
</div>
)
}