how to use useMediaQuery in class component
You're not supplying the args
needed for useMediaQuery
, so Main
is passed as the args
, and a function that expects the component is returned. When React tried to render (call the function), the return value is another function, which is not value as a react child.
Call the function - withMediaQuery
and pass it the media queries, and then pass Main
to the returned function.
Example:
export default withStyles(styles)(withMediaQuery('(min-width:600px)')(Main));
Instead of limiting yourself to only one media query a better withMediaQuery HOC could be
import React from 'react'
import useMediaQuery from '@material-ui/core/useMediaQuery'
export const withMediaQuery = (queries = []) => Component => props => {
const mediaProps = {}
queries.forEach(q => {
mediaProps[q[0]] = useMediaQuery(q[1])
})
return <Component {...mediaProps} {...props} />
}
This would allow you to pass in multiple queries as an array of arrays. Each entry would be a prop name and then the query.
export default withStyles(styles)(withMediaQuery([
['isDesktop', theme => theme.breakpoints.up('lg'), {
defaultMatches: true
}]
]))
In your component you could then request the prop names directly in render
render() {
const { classes, children, IsDesktop = false } = this.props;
const shouldOpenSidebar = IsDesktop ? true : this.state.openSidebar;
return (
<div
className={cc({
[classes.root]: true,
[classes.shiftContent]: isDesktop,
})}>
<Topbar
onSidebarOpen={this.handleSidebarOpen}
/>
<Sidebar
onClose={this.handleSidebarClose}
open={shouldOpenSidebar}
variant={isDesktop ? 'persistent' : 'temporary'}
/>
<main className={classes.content}>
{children}
</main>
</div>
);
}