How to hide a button when printing using react and styled components?

Viewed 2502

i want to hide print button on clicking print button in the page. basically hide the print button on the web page once printing starts.

below is my code,

const printItems = () => {
    window.print();
}

function ItemsTable() {
    return(
        <>
            <TableCell>
                <span>first</span>
            </TableCell>
            <PrintCell>
                <CircleIconButton
                    name="print"
                    onClick={printItems}
                >
            </PrintCell>
        </>
    ); 
}

const TableCell = styled.div`
    display: flex;
    flex-direction: row;
`;

const PrintCell = styled(TableCell)`
    width: 100px;
    justify-content: flex-end;
`;

const CircleIconButton = styled(IconButton)`
    border-radius: 15px;
    background: none;
    width: 32px;
    height: 32px;
`;

Now i want to hide the PrintCell when user clicks CircleIconButton. how can i do it with css and media print.

could someone help me with this? thanks.

2 Answers

You have various solutions:

Conditional rendering

function ItemsTable() {
  const [isPrinting, setIsPrinting] = useState(false);

  const printItems = () => {
    setIsPrinting(true);
    window.print();
  };

  return (
    <>
      {!isPrinting && (
        <PrintCell>
          <CircleIconButton name="print" onClick={printItems} />
        </PrintCell>
      )}
    </>
  );

Using CSS Variable

function ItemsTable() {
  const [isPrinting, setIsPrinting] = useState(false);

  const printItems = () => {
    setIsPrinting(true);
    window.print();
  };

  return (
    <>
      <PrintCell isVisible={isPrinting}>
        <CircleIconButton name="print" onClick={printItems} />
      </PrintCell>
    </>
  );
}

// Or any other css prop like `visible`
const PrintCell = styled(TableCell)`
    display: ${props => props.isVisible ? 'block' : 'none'}
`;

Using Ref

function ItemsTable() {
  const printRef = useRef();

  const printItems = () => {
    printRef.current.style.display = 'none';
    window.print();
  };

  return (
    <>
      <PrintCell ref={printRef}>
        <CircleIconButton name="print" onClick={printItems} />
      </PrintCell>
    </>
  );
}

Using Media Query

const Container = styled.div`
  @media print {
    ${PrintCell} {
      display: none;
    }
  }
`;

const PrintCell = styled(TableCell)`
    width: 100px;
    justify-content: flex-end;
`;

<Container>
  <PrintCell>
    <CircleIconButton name="print" onClick={printItems} />
  </PrintCell>
</Container>

There is no "recommended way", pick the one that suits you, it depends on the situation.

You can use CSS media query to fix the issue with @media print, like if your button class name print_btn then you can set

@media print{
.print_btn{
display:none;
}
}
Related