Skip to content

Commit

Permalink
fix(header): dropdown disappears after window resize #116
Browse files Browse the repository at this point in the history
  • Loading branch information
ichim-david committed Mar 23, 2022
2 parents f10a7a8 + b50fa58 commit fc7dd8b
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 12 deletions.
19 changes: 7 additions & 12 deletions src/ui/Header/Header.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,29 +37,24 @@ const TopDropdownMenu = ({
id,
mobileText,
text,
viewportWidth,
}) => {
const isMobile = viewportWidth < 480;

const Component = ({ mobileText }) => (
<Dropdown
id={id}
className={cx(className, {
'mobile or lower hidden': !mobileText ?? false,
'mobile only': mobileText ?? false,
})}
className={className}
text={mobileText || text}
icon={icon || 'chevron down'}
aria-label="dropdown"
>
<Dropdown.Menu role="group">{children}</Dropdown.Menu>
</Dropdown>
);
if (typeof window !== 'undefined') {
const resolution = window?.innerWidth;
const isMobile = resolution < 480;
return (
<>{isMobile ? <Component mobileText={mobileText} /> : <Component />}</>
);
}
return null;
return (
<>{isMobile ? <Component mobileText={mobileText} /> : <Component />}</>
);
};

const Main = ({
Expand Down
23 changes: 23 additions & 0 deletions src/ui/Header/Header.stories.js
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,26 @@ const menuItems = [
},
];

const debounce = (func) => {
let timer;
return (event) => {
if (timer) clearTimeout(timer);
timer = setTimeout(func, 50, event);
};
};

const Template = (args) => {
const [viewportWidth, setWidth] = React.useState(
typeof window !== 'undefined' && window.innerWidth,
);
React.useEffect(() => {
const handleWindowResize = window.addEventListener('resize', () =>
debounce(setWidth(window.innerWidth)),
);

return () => window.removeEventListener('resize', handleWindowResize);
}, []);

const { languages, links, linksMenuTitle, menuItems } = args;

const [language, setLanguage] = React.useState('en');
Expand All @@ -262,6 +281,7 @@ const Template = (args) => {
icon="chevron down"
aria-label="dropdown"
className=""
viewportWidth={viewportWidth}
>
<div className="content">
<p>
Expand All @@ -286,6 +306,7 @@ const Template = (args) => {
id="theme-sites"
className="tablet or lower hidden"
text={linksMenuTitle}
viewportWidth={viewportWidth}
>
<div className="wrapper">
{links.map((item, index) => (
Expand All @@ -308,9 +329,11 @@ const Template = (args) => {
id="language-switcher"
className="item"
text={`${language.toUpperCase()}`}
mobileText={`${language.toUpperCase()}`}
icon={
<Image src={globeIcon} alt="language dropdown globe icon"></Image>
}
viewportWidth={viewportWidth}
>
<div className="wrapper">
{languages.map((item, index) => (
Expand Down

0 comments on commit fc7dd8b

Please sign in to comment.