Part 08 / Topic 5 of 6
Forwarding a ref through a custom component - verified against [email protected]
ref only works out of the box on the built-in DOM elements this course has used it on so far (<input>, <section>). A custom component - a function you wrote - needs to explicitly accept a ref and pass it down to whichever DOM node it actually wraps, or the parent's ref ends up pointing at nothing. The idiom for doing that changed in React 19, and this course's installed version ([email protected], see TOOLING.md) was checked directly rather than assumed:
// examples/05_ref_as_prop_react19.jsx - React 19 idiom
export function PincodeInputModernRef({ ref, ...inputProps }) {
return <input placeholder="Pincode" {...inputProps} ref={ref} />;
}
// pre-19 idiom, still supported
export const PincodeInputLegacyForwardRef = forwardRef(function PincodeInputLegacyForwardRef(
inputProps,
ref,
) {
return <input placeholder="Pincode" {...inputProps} ref={ref} />;
});
PincodeInputModernRef is a plain function component that simply declares ref as one of its props, exactly like placeholder or any other - no forwardRef import, no wrapper call. A small local probe confirmed this directly: rendering <PincodeInputModernRef ref={someRef} /> really attaches someRef.current to the underlying <input> DOM node, with no console warning or error of any kind (examples/05_ref_as_prop_react19.test.jsx). Before React 19, writing a component this way left ref silently absent from props, and the only way to receive a ref was the forwardRef wrapper on the right - which was verified to still work identically on this installed version (forwardRef is not removed, just no longer necessary). Rule for this course going forward: write new custom components the plain-prop way shown on the left; only reach for forwardRef when reading or maintaining code written before this change.
๐ Going deeper: this repo's own
examples/02_autofocus_search_box.jsxand03_scroll_to_section_nav.jsxnever needed either idiom, becauserefon a built-in element (<input>,<section>) has always worked without forwarding - forwarding only matters the moment a ref needs to reach through a component you wrote, down to the DOM node it wraps.
Done here? The practice set for Part 8 โ including the solutions โ is on the part page.