react-flexbox-grid icon indicating copy to clipboard operation
react-flexbox-grid copied to clipboard

Breakpoint HOC

Open nicholasc opened this issue 7 years ago • 1 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.

nicholasc avatar Jun 12 '17 19:06 nicholasc

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>)
    }
  }
}

bristoljon avatar Nov 16 '17 10:11 bristoljon