A component doesn’t expose its DOM nodes by default. You can opt into exposing a DOM node by using forwardRef and passing the second ref argument down to a specific node.
By default, each component’s DOM nodes are private. However, sometimes it’s useful to expose a DOM node to the parent—for example, to allow focusing it. To opt in, wrap your component definition into forwardRef().
forwardRef() returns a React component that you can render in JSX. Unlike React components defined as plain functions, a component returned by forwardRef
is also able to receive a ref
prop.
Example
import { forwardRef, useRef } from 'react';
export default function ForwardRefDemo() {
const selectControl = useRef(null);
const Select = forwardRef(({ onChange, onBlur, name }, ref) => (
<>
<select name={name} ref={ref} onChange={onChange} onBlur={onBlur}>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
</select>
</>
));
return (
<form onSubmit={(e) => {
e.preventDefault();
console.log(selectControl.current)
console.log(selectControl.current.value)
}}>
<label>Name: </label>
<input name="name" label="Name" required /><br />
<label>Age: </label>
<Select name="age" label="Age" ref={selectControl} /><br />
<input type="submit" /><br />
</form>
);
}