cf.completefrontend

ConceptMedium

How do you focus an input or scroll to an element right after a state change?

Clicking the tea's name should turn it into an input with the cursor in it. This version throws. Why, and how do you fix it?

The code
function TeaName({ name }) {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef(null);
 
  function startEditing() {
    setEditing(true);
    inputRef.current.focus();
  }
 
  return editing ? (
    <input ref={inputRef} defaultValue={name} />
  ) : (
    <button onClick={startEditing}>{name}</button>
  );
}

The answer

Answer it out loud first, the way you would in the interview. Then compare.

Checking your sign-in…