react runtime_error ai_generated true

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

ID: react/ref-object-not-initialized

Also available as: JSON · Markdown · 中文
87%Fix Rate
83%Confidence
1Evidence
2023-05-12First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
React 16.8+ active
React 17.0.2 active
React 18.2.0 active

Root Cause

Attempting to access .current on a ref that is null, often because useRef() was called with no initial value or the ref was not properly attached to a DOM element.

generic

中文

尝试访问 null 的 ref 上的 .current 属性,通常是因为 useRef() 调用时没有初始值,或者 ref 未正确附加到 DOM 元素。

Official Documentation

https://reactjs.org/docs/hooks-reference.html#useref

Workarounds

  1. 90% success Ensure the ref is attached to a DOM element: const myRef = useRef(null); return <div ref={myRef}>...</div>. Then access myRef.current only after the component mounts, e.g., inside useEffect or an event handler.
    Ensure the ref is attached to a DOM element: const myRef = useRef(null); return <div ref={myRef}>...</div>. Then access myRef.current only after the component mounts, e.g., inside useEffect or an event handler.
  2. 85% success If using forwardRef, make sure the child component forwards the ref to a DOM element: const Child = forwardRef((props, ref) => <input ref={ref} />);
    If using forwardRef, make sure the child component forwards the ref to a DOM element: const Child = forwardRef((props, ref) => <input ref={ref} />);

中文步骤

  1. Ensure the ref is attached to a DOM element: const myRef = useRef(null); return <div ref={myRef}>...</div>. Then access myRef.current only after the component mounts, e.g., inside useEffect or an event handler.
  2. If using forwardRef, make sure the child component forwards the ref to a DOM element: const Child = forwardRef((props, ref) => <input ref={ref} />);

Dead Ends

Common approaches that don't work:

  1. Setting useRef(null) explicitly 40% fail

    If the ref is not attached to a DOM element, it remains null. The fix is to attach it, not to change the initial value.

  2. Using useEffect to check if ref.current exists 50% fail

    A null check only masks the error; the underlying issue (ref not attached) persists.

  3. Using createRef() instead of useRef() 60% fail

    createRef() returns { current: null } in function components and will not persist across renders; it's for class components.