Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use media print within Reactjs web app

I would like to hide a div when print preview happens but I find it almost impossible to do it in a React.

<div className="contacts"></div>

Is there any possibilities that I can add pure css or if React Stylesheet supports @media print and hide element with class name contacts when print preview.

I was reading this article https://blog.logrocket.com/the-best-react-inline-style-libraries-comparing-radium-aphrodite-emotion-849ef148c473 but it just seems too much work for something that I would do poorly in css within a matter of seconds.

Any idea how can I achieve such thing in Reactjs?

like image 669
Mizlul Avatar asked Oct 18 '18 19:10

Mizlul


People also ask

Can we use media query in React JS?

Generally, one can not do inline styling with media queries because React doesn't allow us to use media queries in inline styling. We can use radium which is a third-party package that enables media queries for inline styling.

How do I print an image in React JS?

Use onClick event to handle a function that can use to download and print the image.


2 Answers

Inline media queries are not possible. The closest you can get is inlining a stylesheet, like so (in React syntax):

<div className="contacts">
  <style>
    {`@media print {.contacts{display: none;}}`}
  </style>
</div>
like image 76
Ted Avatar answered Nov 03 '22 11:11

Ted


A bit old but maybe it will be useful for someone. If you want to use React styles you can also do:

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    contacts:{
      display: "block",
    },
    [`@media print`]: {
      contacts:{
        display: "none",
      },
    }
  }))
...
const classes = useStyles();
...
<div className={classes.contacts}></div>

This markup works for me with FunctionComponents flawlesly.

like image 38
kyjanond Avatar answered Nov 03 '22 10:11

kyjanond