yocontra / react-responsive

CSS media queries in react - for responsive design, and more.
https://contra.io/react-responsive
MIT License
7.04k stars 298 forks source link

Example for HOC decorator #247

Closed vertic4l closed 4 years ago

vertic4l commented 4 years ago

Could someone provide an example of how to use it within a HOC decorator? Tried to make one with TypeScript, but it's not that easy :D

like:

@withMediaQuery
class SomeComponent extends React.Component
yocontra commented 4 years ago

@vertic4l What do you imagine the API for this looking like?

Something like this?

@withMediaQuery({
  someMode: 'min-width: 100px',
  otherMode: 'min-height: 200px'
})
class SomeComponent extends React.Component {
  static propTypes = {
    someMode: PropTypes.boolean,
    otherMode: PropTypes.boolean
  }
}
vertic4l commented 4 years ago

@contra

I'd like to have something like:

@withMediaQueries
class SomeComponent extends React.Component {
    public render() {
        return (
            <div>
                {this.props.isDesktop && <DesktopComponent />
                {this.props.isTablet && <TabletComponent />
            </div>
        );
    }
}

Reason is i do want to have one place where breakpoints are set and consume it in all relevant components this way.

vertic4l commented 4 years ago

Well, it's okay how it is i guess...

import React from 'react'
import { MediaQuery } from 'react-responsive'

const Example = () => {

  const handleMediaQueryChange = (matches) => {
    // matches will be true or false based on the value for the media query
  }

  return (
    <MediaQuery minDeviceWidth={1224} onChange={handleMediaQueryChange}>
      ...
    </MediaQuery>
  )
}

I can use a Enum here as well which provides a set of breakpoints like:

export enum Breakpoints {
    desktop = 1024,
    tablet = 768,
    mobile = 0,
}

<MediaQuery minDeviceWidth={Breakpoints.desktop} onChange={handleMediaQueryChange}>
    ...
</MediaQuery>
yocontra commented 4 years ago

@vertic4l Yeah you should pretty easily be able to throw together a HOC using the hooks API and your own breakpoint definitions. If you have any trouble doing that let me know.

vertic4l commented 4 years ago

I find it somehow difficult to establish a HOC which adds some props and could find a good example which uses TypeScript for it.