Skip to content

Commit

Permalink
feat: add autoFocus to RadioButton
Browse files Browse the repository at this point in the history
  • Loading branch information
chensara committed Apr 10, 2024
1 parent 2dfef96 commit 659d0e6
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion packages/core/src/components/RadioButton/RadioButton.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import cx from "classnames";
import React, { forwardRef, useCallback, useMemo, useRef } from "react";
import React, { forwardRef, useCallback, useEffect, useMemo, useRef } from "react";
import useMergeRef from "../../hooks/useMergeRef";
import Clickable from "../Clickable/Clickable";
import Text from "../Text/Text";
Expand Down Expand Up @@ -27,6 +27,8 @@ export interface RadioButtonProps extends VibeComponentProps {
value?: string;
/** A string specifying a name for the input control. This name is submitted along with the control's value when the form data is submitted. */
name?: string;
/** is autoFocus */
autoFocus?: boolean;
/** is disabled */
disabled?: boolean;
/** why the input is disabled */
Expand Down Expand Up @@ -64,6 +66,7 @@ const RadioButton: VibeComponent<RadioButtonProps, HTMLElement> & object = forwa
*/
radioButtonClassName,
disabled = false,
autoFocus = false,
disabledReason,
defaultChecked = false,
children,
Expand All @@ -80,6 +83,16 @@ const RadioButton: VibeComponent<RadioButtonProps, HTMLElement> & object = forwa
const inputRef = useRef<HTMLInputElement | null>();
const mergedRef = useMergeRef(ref, inputRef);
const overrideClassName = backwardCompatibilityForProperties([className, componentClassName]);

useEffect(() => {
if (!inputRef?.current || !autoFocus) {
return;
}

const animationFrame = requestAnimationFrame(() => inputRef.current.focus());
return () => cancelAnimationFrame(animationFrame);
}, [inputRef, autoFocus]);

const onChildClick = useCallback(() => {
if (disabled || !retainChildClick) return;
if (inputRef.current) {
Expand Down Expand Up @@ -114,6 +127,7 @@ const RadioButton: VibeComponent<RadioButtonProps, HTMLElement> & object = forwa
type="radio"
value={value}
name={name}
autoFocus={autoFocus}
disabled={disabled}
{...checkedProps}
onChange={onSelect}
Expand Down

0 comments on commit 659d0e6

Please sign in to comment.