0

We have to print a Barcode in a 40mm × 25mm page. As React by default does not support @media or @page in the inline style={{}} attribute we had to add a CSS file into that component:

import "./MyComponent.css";

const MyComponent = (props) => {
    return <div>BARCODE HERE</div>
}

The code in MyComponent.css is like below:

@page {
   size: 40mm 20mm;
   margin: 0;
   padding: 0;
}

The problem is, this stylesheet is interfering with other components too. We tried putting this CSS inside a class, which does not work (even not for the dedicated component):

/* ❌ DOES NOT WORK */
.my-component {
   @page {
      size: 40mm 20mm;
      margin: 0;
      padding: 0;
   }
}

We can undo this by declaring @page in every other component, which will be an overkill for us.

How can we load this stylesheet only to that particular component?

What have we tried so far

CSS Modules

As we are not doing anything with class and we've shown that, @page inside a class won't work, so we cannot use the CSS modules concept as mentioned here.

Styled Components

We tried 'styled-components' like below:

import React from 'react';
import styled from 'styled-components';

const Container = styled.div`
  @page {
    size: 40mm 25mm;
    margin: 0;
    padding: 0;
  }

  /* other container styles */
`;

const MyComponent = () => {
  return (
    <Container>
      <div>BARCODE HERE</div>
    </Container>
  );
};

export default MyComponent;

But we failed. It's not solving the issue. The style here, even within a specified <Container> is intefering with other components as well.

Mayeenul Islam
  • 4,532
  • 5
  • 49
  • 102

1 Answers1

0

There is no straight solution from React. Here's a makeshift solution using Vanilla javascript provided by "gu mingfeng". This code will add a <style> tag into the <head> tag of the page, and then remove the tag while the component is absent (unmounted).

I'm providing the functional component approach to this solution:

let style:any = "";

// Instead of raw-loader we're putting our style in a string.
const BarcodeStyles = `
    @page {
        size: 39mm 25mm;
        margin: 0;
        padding: 0;
    }

    html, body {
        height: 100vh;
        overflow: hidden;
    }
`;

useEffect(() => {
    addStyle(BarcodeStyles);

    return () => {
        removeStyle();
    }
}, []);

function addStyle(content) {
    const styleElement = document.createElement("style");
    styleElement.innerHTML = content;

    style = document.head.appendChild(styleElement);
}

function removeStyle() {
    document.head.removeChild(style);
}

Thanks to my colleague Mr. Harun for finding the way out and helping structuring the content.

Mayeenul Islam
  • 4,532
  • 5
  • 49
  • 102