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.