forwardRef2 function
ReactComponentFactoryProxy
forwardRef2(
- DartForwardRefFunctionComponent wrapperFunction, {
- String? displayName,
Automatically passes a Ref through a component to one of its children.
Example 1: Forwarding refs to DOM components
import 'dart:html';
import 'package:react/react.dart' as react;
// ---------- Component Definition ----------
final FancyButton = react.forwardRef2((props, ref) {
return react.button({'ref': ref, 'className': 'FancyButton'}, 'Click me!');
}, displayName: 'FancyButton');
// ---------- Component Consumption ----------
void main() {
final ref = createRef<Element>();
react_dom.render(FancyButton({'ref': ref}));
// You can now get a ref directly to the DOM button:
final buttonNode = ref.current;
}
Example 2: Forwarding refs in higher-order components
import 'dart:html';
import 'package:react/react.dart' as react;
import 'package:react/react_client.dart' show setClientConfiguration, ReactJsComponentFactoryProxy;
import 'package:react/react_dom.dart' as react_dom;
// ---------- Component Definitions ----------
final FancyButton = react.forwardRef2((props, ref) {
return react.button({'ref': ref, 'className': 'FancyButton'}, 'Click me!');
}, displayName: 'FancyButton');
class _LogProps extends react.Component2 {
@override
void componentDidUpdate(Map prevProps, _, [__]) {
print('old props: $prevProps');
print('new props: ${this.props}');
}
@override
render() {
final propsToForward = {...props}..remove('forwardedRef');
// Assign the custom prop `forwardedRef` as a ref on the component passed in via `props.component`
return props['component']({...propsToForward, 'ref': props['forwardedRef']}, props['children']);
}
}
final _logPropsHoc = react.registerComponent2(() => _LogProps());
final LogProps = react.forwardRef2((props, ref) {
// Note the second param "ref" provided by react.forwardRef2.
// We can pass it along to LogProps as a regular prop, e.g. "forwardedRef"
// And it can then be attached to the Component.
return _logPropsHoc({...props, 'forwardedRef': ref});
// Optional: Make the displayName more useful for the React dev tools.
// See: https://reactjs.org/docs/forwarding-refs.html#displaying-a-custom-name-in-devtools
}, displayName: 'LogProps(${_logPropsHoc.type.displayName})');
// ---------- Component Consumption ----------
void main() {
setClientConfiguration();
final ref = react.createRef<Element>();
react_dom.render(LogProps({'component': FancyButton, 'ref': ref}),
querySelector('#idOfSomeNodeInTheDom'));
// You can still get a ref directly to the DOM button:
final buttonNode = ref.current;
}
Implementation
ReactComponentFactoryProxy forwardRef2(
DartForwardRefFunctionComponent wrapperFunction, {
String? displayName,
}) =>
ReactDartWrappedComponentFactoryProxy.forwardRef(wrapperFunction, displayName: displayName);