Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Docs: ForwardRef convention #27880

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions contributingGuides/STYLE.md
Original file line number Diff line number Diff line change
Expand Up @@ -491,6 +491,19 @@ When writing a function component you must ALWAYS add a `displayName` property a
export default Avatar;
```

## Forwarding refs

When forwarding a ref define named component and pass it directly to the `forwardRef`. By doing this we remove potential extra layer in React tree in form of anonymous component.

```javascript
function FancyInput(props, ref) {
...
return <input {...props} ref={ref} />
}

export default React.forwardRef(FancyInput)
```

## Stateless components vs Pure Components vs Class based components vs Render Props - When to use what?

Class components are DEPRECATED. Use function components and React hooks.
Expand Down
26 changes: 15 additions & 11 deletions contributingGuides/TS_CHEATSHEET.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,24 +43,28 @@
- [1.2](#forwardRef) **`forwardRef`**

```ts
import { forwardRef, useRef, ReactNode } from "react";
// CustomTextInput.tsx

import { forwardRef, useRef, ReactNode, ForwardedRef } from "react";
import { TextInput, View } from "react-native";

export type CustomTextInputProps = {
label: string;
children?: ReactNode;
};

const CustomTextInput = forwardRef<TextInput, CustomTextInputProps>(
(props, ref) => {
return (
<View>
<TextInput ref={ref} />
{props.children}
</View>
);
}
);
function CustomTextInput(props: CustomTextInputProps, ref: ForwardedRef<TextInput>) {
return (
<View>
<TextInput ref={ref} />
{props.children}
</View>
);
};

export default forwardRef(CustomTextInput);

// ParentComponent.tsx

function ParentComponent() {
const ref = useRef<TextInput>();
Expand Down
Loading