javascript / intermediate
Snippet
Forwarding Refs to Child Components
By default, you cannot pass a 'ref' attribute to functional components because they don't have instances. 'forwardRef' wraps a component, allowing it to receive a ref as a second argument and attach it to a specific internal DOM element or component.
snippet.js
1
2
3
4
5
6
7
8
9
import { forwardRef } from 'react';const CustomInput = forwardRef((props, ref) => (<div className="input-wrapper"><input {...props} ref={ref} className="styled-input" /></div>));// Usage: const inputRef = useRef(); <CustomInput ref={inputRef} />
react
Breakdown
1
const CustomInput = forwardRef((props, ref) => ...
Wraps the component function to expose the 'ref' argument alongside 'props'.
2
<input {...props} ref={ref} ... />
Attaches the incoming ref directly to the native HTML input element.