As outlined in the definitions:
function forwardRef<T, P = {}>(Component: RefForwardingComponent<T, P>): ComponentType<P & ClassAttributes<T>>;
interface RefForwardingComponent<T, P = {}> {
(props: P & { children?: ReactNode }, ref?: Ref<T>): ReactElement<any> | null;
propTypes?: ValidationMap<P>;
contextTypes?: ValidationMap<any>;
defaultProps?: Partial<P>;
displayName?: string;
}
The argument ref
is optional, you can try the following:
To create a ref object within a class with your desired target type (div
or View
in react-native), use:
private divRef: React.RefObject<div> = React.createRef();
In the props interface for the forwarded component, expose it as an optional property:
interface Props {
ref?: React.RefObject<div>;
}
Define the forwarded component using React.ComponentType
:
const ComponentWithForwardedRef: React.ComponentType<Props> =
React.forwardRef((props: Props, ref?: React.Ref<div>) => (
<div ref={ref}>{props.message}</div>
));
When creating an instance of the component with the forwarded ref, pass the created ref object as a prop:
<ComponentWithForwardedRef ref={this.divRef} />
Alternatively, bring everything together into one place:
import * as React from "react";
import { render } from "react-dom";
interface Props {
message: string;
ref?: React.RefObject<div>;
}
const ComponentWithForwardedRef: React.ComponentType<Props> =
React.forwardRef((props: Props, ref?: React.Ref<div>) => (
<div ref={ref}>{props.message}</div>
));
class App extends React.Component<Props> {
private divRef: React.RefObject<div> = React.createRef();
public componentDidMount() {
const div = this.divRef.current;
// Check the console!
console.log(div);
}
public render() {
return (
<ComponentWithForwardedRef ref={this.divRef} {...this.props} />
)
}
}
render(<App message="hello world" />, document.getElementById("root"));
Link for future reference: https://codesandbox.io/s/6v152q394k
Dependencies (for reference purposes)
"@types/react": "^16.3.11",
"@types/react-native": "^0.55.19",
"react-native": "0.55.2",
"typescript": "^2.8.1"