Skip to content

Instantly share code, notes, and snippets.

@Kikobeats
Last active Feb 26, 2020
Embed
What would you like to do?
Hide + rebass
import styled from 'styled-components'
import { theme } from 'rebass'
const { breakpoints } = theme
const lastIndex = breakpoints.length - 1
const getMediaBreakpoint = (breakpoints, breakpoint, index) => {
if (index === 0) return `@media screen and (max-width: ${breakpoint})`
const prevBreakpoint = breakpoints[index - 1]
if (index === lastIndex) {
return `@media screen and (min-width: ${prevBreakpoint})`
}
return `@media screen and (min-width: ${prevBreakpoint}) and (max-width: ${breakpoint})`
}
const mediaBreakpoints = breakpoints.reduce((acc, breakpoint, index) => {
acc[index] = getMediaBreakpoint(breakpoints, breakpoint, index)
return acc
}, {})
const hidden = key => props => {
const breakpoints = [].concat(props.breakpoints)
return breakpoints.includes(key)
? {
[mediaBreakpoints[key]]: {
display: 'none'
}
}
: null
}
const Hide = styled.div(
[],
...Object.keys(mediaBreakpoints).map(i => hidden(Number(i)))
)
export default Hide
@Kikobeats
Copy link
Author

Kikobeats commented Mar 7, 2018

Inspired by hidden-styled, I'm trying to do the same but inside rebass world

expected API

<Hide breakpoints={[0]}>I‘m hidden on extra small screens</Hide>
<Hide breakpoints={[1]}>I‘m hidden on small screens</Hide>
<Hide breakpoints={[2]}>I‘m hidden on medium screens</Hide>
<Hide breakpoints={[3]}>I‘m hidden on large screens</Hide>
<Hide breakpoints={[2, 3]}>I‘m hidden on medium and large screens</Hide>

Copy link

ghost commented Apr 23, 2018

This is awesome, exactly what I was trying to achieve.

@ferMartz
Copy link

ferMartz commented Apr 25, 2018

🙌 Thanks @Kikobeats. Great snippet!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment