Skip to content

Instantly share code, notes, and snippets.

@eldh
Last active August 29, 2015 14:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eldh/32eca03738766cd05a8f to your computer and use it in GitHub Desktop.
Save eldh/32eca03738766cd05a8f to your computer and use it in GitHub Desktop.
React breakpoints mixin
Style = require '../styles/props'
_ = require 'lodash'
module.exports =
_setScreenWidth: ->
if @isMounted() then @setState {screenWidth: window.innerWidth}
getInitialState: -> screenWidth: window?.innerWidth or 1280
screenWidth: (minName, maxName) ->
maxIndex = 1 + _.findIndex Style.breakpoints, name: (maxName or minName)
max = Style.breakpoints[maxIndex] or value: Infinity
min = _.find Style.breakpoints, name: minName
(@state.screenWidth >= min.value) and (@state.screenWidth < max.value)
componentWilllUnmount: ->
window.removeEventListener 'resize', @debouncedSetScreenWidth
componentDidMount: ->
@debouncedSetScreenWidth = _.debounce @_setScreenWidth, 300
window.addEventListener 'resize', @debouncedSetScreenWidth
#Example usage
SidebarSmall = React.createFactory require './sidebar-small'
SidebarMedium = React.createFactory require './sidebar-medium'
Breakpoints = require '../mixins/breakpoint-mixin'
{ section } = require 'react-coffee-elements'
module.exports = React.createClass
displayName: 'Sidebar'
mixins: [Breakpoints]
render: ->
if @screenWidth 'xs', 's'
SidebarSmall {}, @props.children
else if @screenWidth 'm'
SidebarMedium {}, @props.children
else
section {className: 'sidebar'}, @props.children
// Generated by Theo
module.exports = {
"breakpoints": [
{"name":"xs","value":0},
{"name":"s","value":550},
{"name":"m","value":850},
{"name":"l","value":1200},
{"name":"xl","value":1650}
],
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment