Skip to content
Open
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
4 changes: 3 additions & 1 deletion src/components/Switch/Switch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ export type Props = {
* Accessibility label for the switch. This is read by the screen reader when the user focuses the switch.
*/
'aria-label'?: string;
ref?: React.RefObject<View | null>;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wdyt about widening ref type to support callback & forwarded refs too?
React.RefObject currently accepts only object refs so passing React.RefCallback<View> / ForwardedRef<View> results in TS error

Suggested change
ref?: React.RefObject<View | null>;
ref?:
| React.RefObject<View | null>
| ((instance: View | null) => void)
| null;

};

const {
Expand Down Expand Up @@ -136,6 +137,7 @@ const Switch = ({
testID,
theme: themeOverrides,
'aria-label': ariaLabel,
ref,
}: Props) => {
const theme = useInternalTheme(themeOverrides);
const reduceMotion = useReduceMotion();
Expand Down Expand Up @@ -346,7 +348,7 @@ const Switch = ({
const iconSize = checked ? SELECTED_ICON : UNSELECTED_ICON;

return (
<View style={[styles.wrapper, style]}>
<View ref={ref} style={[styles.wrapper, style]}>
<Pressable
disabled={disabled}
onPress={() => onValueChange?.(!checked)}
Expand Down
21 changes: 21 additions & 0 deletions src/components/__tests__/Switch.test.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import * as React from 'react';
import type { View } from 'react-native';

import { describe, expect, it, jest } from '@jest/globals';

import { render, screen, userEvent } from '../../test-utils';
Expand Down Expand Up @@ -74,3 +77,21 @@ describe('Switch interaction', () => {
expect(onValueChange).not.toHaveBeenCalled();
});
});

describe('Switch ref', () => {
it('forwards ref to the root view', async () => {
const ref = React.createRef<View>();

await render(<Switch value ref={ref} />);

expect(ref.current).not.toBeNull();
});

it('exposes the measure methods of the root view', async () => {
const ref = React.createRef<View>();

await render(<Switch value ref={ref} />);

expect(typeof ref.current?.measure).toBe('function');
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could we add coverage for a callback ref as well?
both current tests use React.createRef, so they only exercise object refs & wouldn’t catch this type/API regression

});