roylee0704 / react-flexbox-grid

A set of React components implementing flexboxgrid with the power of CSS Modules.

Home Page:http://roylee0704.github.io/react-flexbox-grid/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Breakpoint HOC

nicholasc opened this issue · comments

Hello,

I think it would be nice to have a higher order component that injects the current breakpoint (xs, sm, etc...) as a prop. It would allow for dynamic CSS-in-Javascript with libraries such as styled-component.

Maybe I'm approaching the problem with the wrong thinking... if not, I can get started on this.

Great lib by the way!
Cheers.

I'm looking for similar thing though not sure if this library is the right place for it as the components don't have any concept of the current screen width; they just add css that does. There's this if you use redux or this if not.

I've no experience using either but I did write this HOC to provide the current height and width of a component as props which I use for rendering responsive graphs. It has a debounce interval to prevent excessive re-renders when resizing the screen. No warranty provided but it works for me!

export default function withDimensions(WrappedComponent, { debounceInterval = 250 } = {}) {
  return class WithDimensions extends React.PureComponent {
    constructor(props) {
      super(props)
      this.state = {
        width: 0,
        height: 0,
      }
    }
    componentDidMount() {
      window.onresize = this.debouncedUpdateDims
      setTimeout(this.updateDims, 0)
    }
    componentWillUnmount() {
      window.onresize = null
    }
    setRef = (ref) => {
      this.ref = ref
    }
    updateDims = () => this.setState({
      width: this.ref.offsetWidth,
      height: this.ref.offsetHeight,
    })
    debouncedUpdateDims = () => {
      clearTimeout(this.debounce)
      this.debounce = setTimeout(this.updateDims, debounceInterval)
    }
    render() {
      return (<div ref={this.setRef}>
        <WrappedComponent {...this.state} {...this.props} />
      </div>)
    }
  }
}