Skip to content

Commit

Permalink
Fix Switch ref forwarding (#31629)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
janicduplessis authored and facebook-github-bot committed Jun 2, 2021
1 parent 8ca18f0 commit 1538fa4
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions Libraries/Components/Switch/Switch.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,13 @@ const returnsTrue = () => true;
export default App;
```
*/
export default function Switch(props: Props): React.Node {

const SwitchWithForwardedRef: React.AbstractComponent<
Props,
React.ElementRef<
typeof SwitchNativeComponent | typeof AndroidSwitchNativeComponent,
>,
> = React.forwardRef(function Switch(props, forwardedRef): React.Node {
const {
disabled,
ios_backgroundColor,
Expand All @@ -144,9 +150,11 @@ export default function Switch(props: Props): React.Node {
const trackColorForFalse = trackColor?.false;
const trackColorForTrue = trackColor?.true;

const nativeSwitchRef = React.useRef<?React.ElementRef<
const nativeSwitchRef = React.useRef<React.ElementRef<
typeof SwitchNativeComponent | typeof AndroidSwitchNativeComponent,
>>(null);
> | null>(null);
React.useImperativeHandle(forwardedRef, () => nativeSwitchRef.current);

const [native, setNative] = React.useState({value: null});

const handleChange = (event: SwitchChangeEvent) => {
Expand Down Expand Up @@ -228,4 +236,6 @@ export default function Switch(props: Props): React.Node {
/>
);
}
}
});

export default SwitchWithForwardedRef;

0 comments on commit 1538fa4

Please sign in to comment.