Skip to content

Commit

Permalink
Add onChange callback
Browse files Browse the repository at this point in the history
  • Loading branch information
d4rky-pl committed Apr 21, 2017
1 parent ab7ff5c commit 2c6b00d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ const defaultTypes = {
component: PropTypes.node,
query: PropTypes.string,
values: PropTypes.shape(mediaQuery.matchers),
children: PropTypes.oneOfType([ PropTypes.node, PropTypes.function ])
children: PropTypes.oneOfType([ PropTypes.node, PropTypes.function ]),
onChange: PropTypes.function
}
const mediaKeys = Object.keys(mediaQuery.all)
const excludedQueryKeys = Object.keys(defaultTypes)
Expand Down Expand Up @@ -80,6 +81,12 @@ export default class MediaQuery extends React.Component {
matches: this._mql.matches
})
}

componentDidUpdate(_, prevState) {
if(this.props.onChange && prevState.matches !== this.state.matches) {
this.props.onChange(this.state.matches);
}
}

render() {
if(typeof this.props.children === 'function') {
Expand Down
11 changes: 11 additions & 0 deletions test/index_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,4 +161,15 @@ describe('MediaQuery', function() {
const e = TestUtils.renderIntoDocument(mq);
assert.isNotFalse(TestUtils.findRenderedDOMComponentWithClass(e, 'no-match'));
});
it('calls onChange callback if provided', function() {
const callback = sinon.spy()
const mq = (
<MediaQuery onChange={callback} query="all">
<div className="childComponent"/>
</MediaQuery>
)
const e = TestUtils.renderIntoDocument(mq);
e.setState({ matches: false })
assert.isNotFalse(callback.calledOnce)
})
});

0 comments on commit 2c6b00d

Please sign in to comment.