Skip to content

Commit

Permalink
feat: support nativeElement (#289)
Browse files Browse the repository at this point in the history
  • Loading branch information
zombieJ committed May 17, 2024
1 parent 9b7822b commit 6117050
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export interface CheckboxRef {
focus: (options?: FocusOptions) => void;
blur: () => void;
input: HTMLInputElement | null;
nativeElement: HTMLElement | null;
}

export interface CheckboxProps
Expand All @@ -41,6 +42,8 @@ export const Checkbox = forwardRef<CheckboxRef, CheckboxProps>((props, ref) => {
} = props;

const inputRef = useRef<HTMLInputElement>(null);
const holderRef = useRef<HTMLElement>(null);

const [rawValue, setRawValue] = useMergedState(defaultChecked, {
value: checked,
});
Expand All @@ -53,6 +56,7 @@ export const Checkbox = forwardRef<CheckboxRef, CheckboxProps>((props, ref) => {
inputRef.current?.blur();
},
input: inputRef.current,
nativeElement: holderRef.current,
}));

const classString = classNames(prefixCls, className, {
Expand Down Expand Up @@ -86,7 +90,7 @@ export const Checkbox = forwardRef<CheckboxRef, CheckboxProps>((props, ref) => {
};

return (
<span className={classString} title={title} style={style}>
<span className={classString} title={title} style={style} ref={holderRef}>
<input
{...inputProps}
className={`${prefixCls}-input`}
Expand Down
9 changes: 9 additions & 0 deletions tests/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -273,4 +273,13 @@ describe('Checkbox ref', () => {

expect(ref.current?.input).toBe(inputEl);
});

it('nativeElement should work', () => {
const ref = React.createRef<CheckboxRef>();

const { container } = render(<Checkbox ref={ref} />);
const holderEl = container.querySelector('.rc-checkbox')!;

expect(ref.current?.nativeElement).toBe(holderEl);
});
});

0 comments on commit 6117050

Please sign in to comment.