-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(visible): show an element only in a specific breakpoint
- Loading branch information
1 parent
192ef39
commit 486625e
Showing
2 changed files
with
66 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export { default as Visible } from './Visible'; |