Skip to content

Commit

Permalink
[useButton][base] Fix tabIndex not being forwarded (#38417)
Browse files Browse the repository at this point in the history
  • Loading branch information
DiegoAndai authored Aug 11, 2023
1 parent 27fddcf commit 38b7936
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
42 changes: 42 additions & 0 deletions packages/mui-base/src/useButton/useButton.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -197,4 +197,46 @@ describe('useButton', () => {
});
});
});

describe('tabIndex', () => {
it('does not return tabIndex in getRootProps when host component is BUTTON', () => {
function TestComponent() {
const ref = React.useRef(null);
const { getRootProps } = useButton({ rootRef: ref });

expect(getRootProps().tabIndex).to.equal(undefined);

return <button {...getRootProps()} />;
}

const { getByRole } = render(<TestComponent />);
expect(getByRole('button')).to.have.property('tabIndex', 0);
});

it('returns tabIndex in getRootProps when host component is not BUTTON', () => {
function TestComponent() {
const ref = React.useRef(null);
const { getRootProps } = useButton({ rootRef: ref });

expect(getRootProps().tabIndex).to.equal(ref.current ? 0 : undefined);

return <span {...getRootProps()} />;
}

const { getByRole } = render(<TestComponent />);
expect(getByRole('button')).to.have.property('tabIndex', 0);
});

it('returns tabIndex in getRootProps if it is explicitly provided', () => {
const customTabIndex = 3;
function TestComponent() {
const ref = React.useRef(null);
const { getRootProps } = useButton({ rootRef: ref, tabIndex: customTabIndex });
return <button {...getRootProps()} />;
}

const { getByRole } = render(<TestComponent />);
expect(getByRole('button')).to.have.property('tabIndex', customTabIndex);
});
});
});
4 changes: 4 additions & 0 deletions packages/mui-base/src/useButton/useButton.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,10 @@ export function useButton(parameters: UseButtonParameters = {}): UseButtonReturn

const buttonProps: AdditionalButtonProps = {};

if (tabIndex !== undefined) {
buttonProps.tabIndex = tabIndex;
}

if (hostElementName === 'BUTTON') {
buttonProps.type = type ?? 'button';
if (focusableWhenDisabled) {
Expand Down

0 comments on commit 38b7936

Please sign in to comment.