3

by reading the documentation, I thought the good solution in later material-ui was useMediaQuery, but at best I can't get it right. My goal is to hide a menu when the page is printed, so I wrote something like:

if (!useMediaQuery("print")) {
  ... code to be hidden
}

which compiles an execute fine, but doesn't work. It seems that the component isn't rendered when the browser goes in print preview mode (FF 65).

Any idea on how to acheive this?

sthenault
  • 14,397
  • 5
  • 38
  • 32

4 Answers4

10

At the moment useMediaQuery is unstable doc

⚠️ useMediaQuery is unstable as hooks aren't stable yet, therefore it is exported with an unstable prefix. Please note that it depends on react@next and react-dom@next.

The best option that i found is:

const styles  = {
    myClass:{
        '@media print' : {
            display: 'none'
    }}
}
class MyComponent extends React.Component {
    render() {
        const { classes } = this.props;
        return (
            <div className={classes.myClass}>
                No show on print
            </div>
        );
    }
}
export default withStyles(styles)(MyComponent);
oisti
  • 365
  • 1
  • 8
  • ,thank you for your response. I know useMediaQuery is using hooks, I had to use react 16.8 to get it works. Once this done I supposed it would do the (advertised) job, but I'm maybe actually on an aventurous path. – sthenault Feb 13 '19 at 08:33
3

I believe useMediaQuery works as intended (i.e. not a bug in useMediaQuery), but it leverages window.matchMedia and Firefox doesn't appear to work with using that to drive print differences.

Here's a related question: window.matchMedia('print') failing in Firefox and IE

This simple example works as expected in Chrome, but not Firefox 65.

import React from "react";
import ReactDOM from "react-dom";
import { unstable_useMediaQuery as useMediaQuery } from "@material-ui/core/useMediaQuery";
import "./styles.css";

function App() {
  const matchesPrint = useMediaQuery("print");
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      {matchesPrint && <h2>This should only show for printing.</h2>}
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Edit mz9vpj2v2y

So for Firefox, you need something like oisti's approach.

Ryan Cogswell
  • 75,046
  • 9
  • 218
  • 198
1

Using mUI v5, I define the non printable area in a styled component :

import { styled } from '@mui/material/styles';

const NotPrintable = styled('div')({
  '@media print': {
    display: 'none',
  },
});

export const MyPage = () => (
  <>
    <NotPrintable>
      <SomeComponent />
      <PrintButton />
    </NotPrintable>

    // printable stuff below
  </>
);

-1

as far as I know you need to do it with styles:

Add this guy:

<style type="text/css" media="print">
  .no-print {
    display: none;
  }
</style>

use the "no-print" style on things you don't want to print