Last active
May 8, 2020 10:57
-
-
Save dimaninc/8d75b5f823beae3c8c93e47c3c7f60fa to your computer and use it in GitHub Desktop.
Styled components responsive technique
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
import { css } from 'styled-components'; | |
const breakpoints = { | |
phone: 450, | |
tabletPortrait: 768, | |
laptopTiny: 920, | |
tabletLandscape: 1024, | |
mdpi: 1280, | |
hidpi: 1440, | |
}; | |
// this is used when the breakpoint width is predefined for component | |
const minWidth = Object.keys(breakpoints).reduce((accumulator, label) => { | |
accumulator[label] = (...args) => css` | |
@media (min-width: ${breakpoints[label]}px) { | |
${css(...args)}; | |
} | |
`; | |
return accumulator; | |
}, {}); | |
// and this is used when the breakpoint width is a variable | |
// if the component is reusable and should have different responsive behavior on different screens | |
const minWidthManual = breakpoint => (...args) => css` | |
@media (min-width: ${breakpoint}px) { | |
${css(...args)}; | |
} | |
`; | |
const maxWidth = Object.keys(breakpoints).reduce((accumulator, label) => { | |
accumulator[label] = (...args) => css` | |
@media (max-width: ${breakpoints[label] - 1}px) { | |
${css(...args)}; | |
} | |
`; | |
return accumulator; | |
}, {}); | |
const maxWidthManual = breakpoint => (...args) => css` | |
@media (max-width: ${breakpoint - 1}px) { | |
${css(...args)}; | |
} | |
`; | |
export { breakpoints, minWidth, minWidthManual, maxWidth, maxWidthManual }; |
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
import { breakpoints, maxWidth, maxWidthManual, minWidthManual } from './breakpoints'; | |
// predefenied breakpoint width | |
const SomeComponent = styled.div` | |
display: flex; | |
flex-wrap: wrap; | |
margin-right: 30px; | |
width: 570px; | |
flex-shrink: 0; | |
${maxWidth.mdpi` | |
width: auto; | |
margin-right: 0; | |
flex-wrap: nowrap; | |
`} | |
`; | |
// variable breakpoint width | |
const FlexBreak = styled.div` | |
flex-basis: 100%; | |
height: 0; | |
line-height: 0; | |
font-size: 0; | |
${({ workOnLess }) => minWidthManual(workOnLess)` | |
display: none; | |
`} | |
`; | |
const Block = ({ averageRating, reviewsCount, mobileOnLess }) => ( | |
<Wrapper mobileOnLess={mobileOnLess}> | |
Some text | |
<FlexBreak workOnLess={mobileOnLess} /> | |
Some more text | |
</Wrapper> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment