Skip to content

Commit

Permalink
feat(visible): show an element only in a specific breakpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
mverissimo committed Jun 11, 2020
1 parent 192ef39 commit 486625e
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
65 changes: 65 additions & 0 deletions src/components/Visible/Visible.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import React, { useState, useEffect, Fragment } from 'react';
import { withTheme } from 'emotion-theming';

import { Types } from '../../types';
import { getBreakpoint } from '../../utils/getBreakpoint';

function Visible({
xs,
sm,
md,
lg,
xl,
theme,
children,
}: Types.StyleProps & Types.VisibleProps) {
const [{ screen }, setState] = useState({ screen: 'xs' });

useEffect(() => {
const setScreen = () => {
const currentScreen = getBreakpoint(theme);

if (currentScreen !== screen) {
setState({
screen: currentScreen,
});
}
};

setScreen();

//SSR typecheck
if (typeof window !== 'undefined') {
window.addEventListener('orientationchange', setScreen, false);
window.addEventListener('resize', setScreen, false);
}

return () => {
window.removeEventListener('orientationchange', setScreen);
window.removeEventListener('resize', setScreen);
};
}, [theme, screen]);

const isVisible = () => {
switch (screen) {
case 'xs':
return xs;

case 'sm':
return sm;

case 'md':
return md;

case 'lg':
return lg;

case 'xl':
return xl;
}
};

return isVisible() ? <Fragment>{children}</Fragment> : null;
}

export default withTheme(Visible);
1 change: 1 addition & 0 deletions src/components/Visible/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as Visible } from './Visible';

0 comments on commit 486625e

Please sign in to comment.