Created
November 16, 2018 23:06
-
-
Save danielr18/06abef32acb8b3a129738ae023bc6d1e to your computer and use it in GitHub Desktop.
Semantic's Responsive with styled-jsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import _ from 'lodash' | |
import PropTypes from 'prop-types' | |
import css from 'styled-jsx/css' | |
import { Responsive as SemanticResponsive } from 'semantic-ui-react' | |
import classNames from 'classnames' | |
import hoistNonReactStatics from 'hoist-non-react-statics' | |
class Responsive extends React.Component { | |
static propTypes = { | |
minWidth: PropTypes.number, | |
maxWidth: PropTypes.number, | |
mediaQueryOnly: PropTypes.bool | |
} | |
constructor(props) { | |
this.state = { | |
mounted: false | |
} | |
} | |
componentDidMount() { | |
this.setState({ mounted: true }) | |
} | |
getMediaQueryStyle = () => { | |
const { minWidth, maxWidth } = this.props | |
const isMaxWidthSet = !_.isNil(maxWidth) | |
const isMinWidthSet = !_.isNil(minWidth) | |
if ((!this.props.mediaQueryOnly && this.state.mounted) || (!isMinWidthSet && !isMaxWidthSet)) return css.resolve`` | |
if (isMinWidthSet && !isMaxWidthSet) { | |
return css.resolve` | |
@media screen and (max-width: ${minWidth - 1}px) { | |
.responsive { | |
display: none !important; | |
} | |
} | |
` | |
} else if (isMaxWidthSet && !isMinWidthSet) { | |
return css.resolve` | |
@media screen and (min-width: ${maxWidth + 1}px) { | |
.responsive { | |
display: none !important; | |
} | |
} | |
` | |
} else { | |
return css.resolve` | |
@media screen and (min-width: ${maxWidth + 1}px), (max-width: ${minWidth - 1}px) { | |
.responsive { | |
display: none !important; | |
} | |
} | |
` | |
} | |
} | |
render() { | |
const { mounted } = this.state | |
const mediaQuery = this.getMediaQueryStyle() | |
const { className, minWidth, maxWidth, mediaQueryOnly, ...rest } = this.props | |
const useWidth = !mediaQueryOnly && mounted | |
return ( | |
<React.Fragment> | |
<SemanticResponsive | |
className={classNames('responsive', mediaQuery.className, className)} | |
minWidth={useWidth ? minWidth : null} | |
maxWidth={useWidth ? maxWidth : null} | |
{...rest} | |
/> | |
{mediaQuery.styles} | |
</React.Fragment> | |
) | |
} | |
} | |
hoistNonReactStatics(Responsive, SemanticResponsive) | |
export default Responsive |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment