Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 51 additions & 19 deletions modules/Media.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,42 @@ import PropTypes from "prop-types";
import invariant from "invariant";
import json2mq from "json2mq";

const queryType = PropTypes.oneOfType([
PropTypes.string,
PropTypes.object,
PropTypes.arrayOf(PropTypes.object.isRequired)
]);

/**
* Conditionally renders based on whether or not a media query matches.
*/
class Media extends React.Component {
static propTypes = {
defaultMatches: PropTypes.bool,
query: PropTypes.oneOfType([
PropTypes.string,
PropTypes.object,
PropTypes.arrayOf(PropTypes.object.isRequired)
]).isRequired,
defaultMatches: PropTypes.objectOf(PropTypes.bool),
queries: PropTypes.objectOf(queryType).isRequired,
render: PropTypes.func,
children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
targetWindow: PropTypes.object
};

static defaultProps = {
defaultMatches: true
};
queries = [];

state = {
matches: this.props.defaultMatches
matches:
this.props.defaultMatches ||
Object.keys(this.props.queries).reduce(
(acc, key) => ({ ...acc, [key]: true }),
{}
)
};

updateMatches = () => this.setState({ matches: this.mediaQueryList.matches });
updateMatches = () => {
const newMatches = this.queries.reduce(
(acc, { name, mqList }) => ({ ...acc, [name]: mqList.matches }),
{}
);
this.setState({ matches: newMatches });
};

componentWillMount() {
if (typeof window !== "object") return;
Expand All @@ -39,29 +50,50 @@ class Media extends React.Component {
"<Media targetWindow> does not support `matchMedia`."
);

let { query } = this.props;
if (typeof query !== "string") query = json2mq(query);
const { queries } = this.props;

this.queries = Object.keys(queries).map(name => {
const query = queries[name];
const qs = typeof query !== "string" ? json2mq(query) : query;
const mqList = targetWindow.matchMedia(qs);

mqList.addListener(this.updateMatches);

return { name, qs, mqList };
});

this.mediaQueryList = targetWindow.matchMedia(query);
this.mediaQueryList.addListener(this.updateMatches);
this.updateMatches();
}

componentWillUnmount() {
this.mediaQueryList.removeListener(this.updateMatches);
this.queries.forEach(({ mqList }) =>
mqList.removeListener(this.updateMatches)
);
}

render() {
const { children, render } = this.props;
const { matches } = this.state;

const isAnyMatches = Object.keys(matches).some(key => matches[key]);

return render
? matches ? render() : null
? isAnyMatches
? render(matches)
: null
: children
? typeof children === "function"
? children(matches)
: !Array.isArray(children) || children.length // Preact defaults to empty children array
? matches ? React.Children.only(children) : null
: // Preact defaults to empty children array
!Array.isArray(children) || children.length
? isAnyMatches
? // We have to check whether child is a composite component or not to decide should we
// provide `matches` as a prop or not
React.Children.only(children) &&
typeof React.Children.only(children).type === "string"
? React.Children.only(children)
: React.cloneElement(React.Children.only(children), { matches })
: null
: null
: null;
}
Expand Down
57 changes: 57 additions & 0 deletions modules/__tests__/Media-ssr-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/** @jest-environment node */

import React from "react";
import ReactDOMServer from "react-dom/server";
import Media from "../Media";

describe("A <Media> in server environment", () => {
const queries = {
sm: "(max-width: 1000px)",
lg: "(max-width: 2000px)",
xl: "(max-width: 3000px)"
};

describe("when no default matches prop provided", () => {
it("should render its children as if all queries are matching", () => {
const element = (
<Media queries={queries}>
{matches =>
matches.sm &&
matches.lg &&
matches.xl && <span>All matches, render!</span>
}
</Media>
);

const result = ReactDOMServer.renderToStaticMarkup(element);

expect(result).toBe("<span>All matches, render!</span>");
});
});

describe("when default matches prop provided", () => {
const defaultMatches = {
sm: true,
lg: false,
xl: false
};

it("should render its children according to the provided defaultMatches", () => {
const element = (
<Media queries={queries} defaultMatches={defaultMatches}>
{matches => (
<div>
{matches.sm && <span>small</span>}
{matches.lg && <span>large</span>}
{matches.xl && <span>extra large</span>}
</div>
)}
</Media>
);

const result = ReactDOMServer.renderToStaticMarkup(element);

expect(result).toBe("<div><span>small</span></div>");
});
});
});
Loading