Skip to content

Instantly share code, notes, and snippets.

@fmoliveira
Created May 28, 2020 19:25
Show Gist options
  • Save fmoliveira/77513eb0980c163c994d6f4ab83f0f92 to your computer and use it in GitHub Desktop.
Save fmoliveira/77513eb0980c163c994d6f4ab83f0f92 to your computer and use it in GitHub Desktop.
Storybook Decorator for Auto Focus
import React, { useCallback } from 'react';
/**
* Storybook Decorator
*
* Auto click the first focusable element.
*/
const AutoFocusStory = (storyFn: () => {} | null | undefined) => {
const autofocus = useCallback((node: HTMLDivElement) => {
const element = node.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
if (element instanceof HTMLElement) {
element.click();
}
}, []);
return (
<div ref={autofocus}>
{storyFn()}
</div>
);
};
export default AutoFocusStory;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment