Skip to content

Commit 1538fa4

Browse files
janicduplessisfacebook-github-bot
authored andcommitted
Fix Switch ref forwarding (#31629)
Summary: Since moving Switch to a function component it is no longer possible to get the native switch ref. This adds forwardRef so it is possible again. ## Changelog [General] [Fixed] - Fix Switch ref forwarding Pull Request resolved: #31629 Test Plan: Tested the change in an app using react-native-gesture-handler, which tries to set a ref on Switch. Also made sure flow still passes. Reviewed By: TheSavior Differential Revision: D28839605 Pulled By: lunaleaps fbshipit-source-id: 1fee86145caeabb60c0010bb9062dddca419f7ca
1 parent 8ca18f0 commit 1538fa4

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

Libraries/Components/Switch/Switch.js

+14-4
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,13 @@ const returnsTrue = () => true;
129129
export default App;
130130
```
131131
*/
132-
export default function Switch(props: Props): React.Node {
132+
133+
const SwitchWithForwardedRef: React.AbstractComponent<
134+
Props,
135+
React.ElementRef<
136+
typeof SwitchNativeComponent | typeof AndroidSwitchNativeComponent,
137+
>,
138+
> = React.forwardRef(function Switch(props, forwardedRef): React.Node {
133139
const {
134140
disabled,
135141
ios_backgroundColor,
@@ -144,9 +150,11 @@ export default function Switch(props: Props): React.Node {
144150
const trackColorForFalse = trackColor?.false;
145151
const trackColorForTrue = trackColor?.true;
146152

147-
const nativeSwitchRef = React.useRef<?React.ElementRef<
153+
const nativeSwitchRef = React.useRef<React.ElementRef<
148154
typeof SwitchNativeComponent | typeof AndroidSwitchNativeComponent,
149-
>>(null);
155+
> | null>(null);
156+
React.useImperativeHandle(forwardedRef, () => nativeSwitchRef.current);
157+
150158
const [native, setNative] = React.useState({value: null});
151159

152160
const handleChange = (event: SwitchChangeEvent) => {
@@ -228,4 +236,6 @@ export default function Switch(props: Props): React.Node {
228236
/>
229237
);
230238
}
231-
}
239+
});
240+
241+
export default SwitchWithForwardedRef;

0 commit comments

Comments
 (0)