react runtime_error ai_generated true

TypeError: Cannot read properties of null (reading 'focus')

ID: react/ref-object-null-on-mount

Also available as: JSON · Markdown · 中文
90%Fix Rate
85%Confidence
1Evidence
2023-05-18First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
React 18.2.0 active
React 19.0.0-rc.2 active

Root Cause

A ref object is null when accessed because the component has not mounted yet or the ref is incorrectly attached to a stateless component.

generic

中文

访问 ref 对象时其为 null,因为组件尚未挂载或 ref 错误地附加到了无状态组件。

Official Documentation

https://react.dev/reference/react/useRef

Workarounds

  1. 95% success Access the ref inside a useEffect hook with an empty dependency array to ensure the component is mounted: useEffect(() => { if (ref.current) { ref.current.focus(); } }, []);
    Access the ref inside a useEffect hook with an empty dependency array to ensure the component is mounted: useEffect(() => { if (ref.current) { ref.current.focus(); } }, []);
  2. 90% success Use a callback ref to handle the ref assignment: const inputRef = useCallback(node => { if (node) { node.focus(); } }, []); <input ref={inputRef} />
    Use a callback ref to handle the ref assignment: const inputRef = useCallback(node => { if (node) { node.focus(); } }, []); <input ref={inputRef} />
  3. 95% success If using a function component, wrap it with React.forwardRef and pass the ref to a DOM element inside: const MyComponent = React.forwardRef((props, ref) => <input ref={ref} />);
    If using a function component, wrap it with React.forwardRef and pass the ref to a DOM element inside: const MyComponent = React.forwardRef((props, ref) => <input ref={ref} />);

中文步骤

  1. Access the ref inside a useEffect hook with an empty dependency array to ensure the component is mounted: useEffect(() => { if (ref.current) { ref.current.focus(); } }, []);
  2. Use a callback ref to handle the ref assignment: const inputRef = useCallback(node => { if (node) { node.focus(); } }, []); <input ref={inputRef} />
  3. If using a function component, wrap it with React.forwardRef and pass the ref to a DOM element inside: const MyComponent = React.forwardRef((props, ref) => <input ref={ref} />);

Dead Ends

Common approaches that don't work:

  1. 90% fail

    The ref is not attached until after the component mounts, so it is null initially.

  2. 70% fail

    This creates a dummy element that is not connected to the DOM, so methods like focus() may not work as expected.

  3. 80% fail

    Function components cannot receive refs directly; they must be wrapped in forwardRef.