Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Media Querys in React using CSS and Wrapper Components
import React, { Component, PropTypes } from 'react';
import MediaQuery from './media-query';
class Example extends Component {
render() {
return (
<div>
<MediaQuery size="mobile">
<h1>Mobile View</h1><
</MediaQuery>
<MediaQuery size="desktop">
<h1>Desktop View</h1>
</MediaQuery>
</div>
);
}
}
export default Example;
import React, { PropTypes } from 'react'
import './styles.scss';
const MediaQuery = ( { size }) => {
return (
<div className={`MediaQuery-${size}`}>
{ this.props.children }
</div>
)
);
MediaQuery.defaultProps = {
size: 'mobile'
}
MediaQuery.propTypes = {
size: React.PropTypes.oneOf(['mobile', 'desktop'])
}
export default MediaQuery;
@media only screen and (min-width: 500px) {
.MediaQuery-mobile{
display: none;
}
}
@media only screen and (max-width: 500px) {
.MediaQuery-desktop{
display: none;
}
}

stk-dmitry commented Nov 20, 2016

Code link

An error occurred with this.props.children
I think the best to use. thanks

const MediaQuery = (props) => {
  const { size, children } = props;
  return (
    <div className={`MediaQuery-${size}`}> {children} </div>
  );
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment