bootstarted / react-resize-observer

Component for giving you `onResize`.
MIT License
48 stars 1 forks source link

Trying to create "breakpoint" classes on the parentNode #23

Open danieltodonnell opened 5 years ago

danieltodonnell commented 5 years ago

I'm trying to implement breakpoints like this article: https://philipwalton.com/articles/responsive-components-a-solution-to-the-container-queries-problem/#observing-container-resizes

Essentially I want the parentNode object to have classes like .SM .MD .LG depending on how big they are. The problem is accessing either the parentNode or embedding content in the children of the . Neither are easy.

The resize and reflow, only return the rect, which is great, but they could easily return the parentNode as well. This would make it much more useful in this usecase. If you embed content as children like <ResizeObserver>{children}</ResizeObserver> then the content isn't passed through.

In the version I'm running locally, I just extend the reflow, resize, position to also return the parentNode. would you guys be open to me creating a PR to extend it to return parentNode as well?

izaakschroeder commented 5 years ago

I'll have to double check, but I'm quite sure:

I think your use case could maybe be boiled down to something like this? Which doesn't need refs at all 😄

class ContentWithBreakpoints extends React.Component {
  state = {width: 0, height: 0}

  _handleReflow = (rect) => {
    this.setState({width: rect.width, height: rect.height});
  }

  render() {
    const {children} = this.props;
    const {width, height} = this.state;
    return (
      <div 
        className={classNames({
          SM: true,
          MD: width > 300,
          LG: width > 500
        })}
      >
        <ResizeObserver onReflow={this._handleReflow}/>
        {children}
      </div>
    );
  }
}

Then instead of <ResizeObserver>{children}</ResizeObserver> you would have:

<ContentWithBreakpoints>{children}</ContentWithBreakpoints>

Which is probably better anyway because then you have all the control in the world – you can do some prop juggling about what the values for SM, MD, LG, etc. are.

If you don't like the fact there's a wrapper div and you'd rather have the observer injected into whatever component you're rendering, you could probably also swing that with render props.

class ContentWithBreakpoints extends React.Component {
  state = {width: 0, height: 0}

  _handleReflow = (rect) => {
    this.setState({width: rect.width, height: rect.height});
  }

  render() {
    const {children} = this.props;
    const {width, height} = this.state;
    const breakpoints = {
      SM: true,
      MD: width > 300,
      LG: width > 500
    };
    return (
      children({observer: <ResizeObserver onReflow={this._handleReflow}/>, breakpoints});
    );
  }
}

and then:

<ContentWithBreakpoints>
  {({observer, breakpoints}) => (
    <div className={...}>{observer}...</div>
  )}
</ContentWithBreakpoints>

/cc @10xjs