Test driving useRef
There's always a chance that React runs short in terms of controlling the internals of a DOM element. Say there's an input and a button, as in Figure 8.4. Upon a button click, we want to manually focus on the input:
Normally, if we click the button, it gets focused, and if we click somewhere else, it loses focus. But in this case, after we click the Focus button, we want to focus the input instead of the button so that the user can type right away.
Let's see how we can apply useRef
to make this happen:
const Title = () => { const ref = useRef() const onClick = () => { ref.current.focus() } return ( <> <input ref={ref} /> <button onClick={onClick}>focus</button> <...