react-spectrum icon indicating copy to clipboard operation
react-spectrum copied to clipboard

Ensure useRadioGroup arrow keys select only radio inputs

Open masad-frost opened this issue 2 years ago • 0 comments

Closes #3536

✅ Pull Request Checklist:

  • [x] Included link to corresponding React Spectrum GitHub Issue.
  • [ ] Added/updated unit tests and storybook for this change (for new code or code which already has tests).
    • I can't find any related tests
  • [x] Filled out test instructions.
  • [x] Updated documentation (if it already exists for this component).
  • [x] Looked at the Accessibility Practices for this feature - Aria Practices

📝 Test Instructions:

  • Use useRadioGroup in a component where there are focusable elements (button) within the group (See code snippet below)
  • Focus a radio
  • Hit arrow keys
  • Focus is never given to buttons, only radio inputs
import {useRadioGroupState} from 'react-stately';
import {useRadio, useRadioGroup} from 'react-aria';

let RadioContext = React.createContext(null);

function RadioGroup(props) {
  let { children, label } = props;
  let state = useRadioGroupState(props);
  let { radioGroupProps, labelProps } = useRadioGroup(props, state);

  return (
    <div {...radioGroupProps}>
      <span {...labelProps}>{label}</span>
      <RadioContext.Provider value={state}>
        {children}
      </RadioContext.Provider>
    </div>
  );
}

function Radio(props) {
  let { children } = props;
  let state = React.useContext(RadioContext);
  let ref = React.useRef(null);
  let { inputProps } = useRadio(props, state, ref);

  return (
    <label style={{ display: 'block' }}>
      <input {...inputProps} ref={ref} />
      <button tabIndex="-1">steal your arrow keys</button>
      {children}
    </label>
  );
}

<RadioGroup label="Favorite pet">
  <Radio value="dogs">Dogs</Radio>
  <Radio value="cats">Cats</Radio>
</RadioGroup>

masad-frost avatar Sep 20 '22 02:09 masad-frost