react
runtime_error
ai_generated
true
TypeError: Cannot read properties of null (reading 'focus')
ID: react/ref-object-null-on-mount
90%Fix Rate
85%Confidence
1Evidence
2023-05-18First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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/useRefWorkarounds
-
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(); } }, []); -
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} /> -
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} />);
中文步骤
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(); } }, []);Use a callback ref to handle the ref assignment: const inputRef = useCallback(node => { if (node) { node.focus(); } }, []); <input ref={inputRef} />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:
-
90% fail
The ref is not attached until after the component mounts, so it is null initially.
-
70% fail
This creates a dummy element that is not connected to the DOM, so methods like focus() may not work as expected.
-
80% fail
Function components cannot receive refs directly; they must be wrapped in forwardRef.