Skip to content

Instantly share code, notes, and snippets.

@mfazekas
Last active July 20, 2022 19:29
Show Gist options
  • Save mfazekas/83c8705baa80f3b20c2e4f720be1ebf7 to your computer and use it in GitHub Desktop.
Save mfazekas/83c8705baa80f3b20c2e4f720be1ebf7 to your computer and use it in GitHub Desktop.
ComponentFC useRef
/* eslint-disable react-native/no-inline-styles */
import React, {
Component,
useRef,
useImperativeHandle,
forwardRef,
} from 'react';
import { View, Button, Text } from 'react-native';
class ComponentC extends React.Component<{ name: string }> {
doSomething() {
console.log(' => ComponentC.doSomething');
}
render() {
return (
<View>
<Text>{this.props.name}</Text>
</View>
);
}
}
type ComponentFCRef = {
doSomething(): void;
};
interface ComponentFCProps {
name: string;
}
const ComponentFC = forwardRef<ComponentFCRef, ComponentFCProps>(function (
props: { name: string },
ref: React.Ref<ComponentFCRef>,
): JSX.Element {
useImperativeHandle(ref, () => ({
doSomething: () => {
console.log(' => ComponentFC.doSomething');
},
}));
return (
<View>
<Text>{props.name}</Text>
</View>
);
});
type ComponentFC = ComponentFCRef;
export default function RefExample() {
const componentCRef = useRef<ComponentC>(null);
const componentFCRef = useRef<ComponentFC>(null);
return (
<View
style={{ backgroundColor: 'white', flex: 1, padding: 20, margin: 20 }}
>
<ComponentC name="Component1" ref={componentCRef} />
<ComponentFC name="Component1" ref={componentFCRef} />
<Button
title="try"
onPress={() => {
console.log(' => try pressed');
componentCRef.current?.doSomething();
componentFCRef.current?.doSomething();
}}
/>
</View>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment