Typeerror for componentRef in ReactJS
I am a beginner in ReactJS and wanting to print a particular div content within the site. From what I have read, the "react-to-print" package should help me for this use case. I have followed several tutorial but I met with an error where I am trying to assign componentRef
with useRef()
This is what I have right now
import React, { createRef, forwardRef, useRef, useState } from "react"
import Barcode from "../barcode/Barcode"
import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap'
import PrintButton from '../buttons/PrintButton'
import ReactToPrint, { PrintContextConsumer, useReactToPrint } from "react-to-print"
import { WindowScrollController } from "@fullcalendar/core"
const PrintModal = forwardRef((props) => {
const [basicModal, setBasicModal] = useState(false)
console.log(&qu开发者_开发技巧ot;data", props)
const componentRef = useRef()
console.log("componentRef", componentRef)
const handlePrint = useReactToPrint({
content: () => componentRef.current,
onafterprint: () => console.log("PRINT BERHASIL")
})
return (
<div className='demo-inline-spacing'>
<div className='basic-modal'>
<Button color='primary' onClick={() => setBasicModal(!basicModal)}>
Print
</Button>
<Modal isOpen={basicModal} toggle={() => setBasicModal(!basicModal)}>
<ModalHeader toggle={() => setBasicModal(!basicModal)}>Print</ModalHeader>
<ModalBody>
<div ref={el => (componentRef=el)}>
/** The content that I want to Print **/
</div>
</ModalBody>
<ModalFooter>
<Button color='primary' onClick={handlePrint}>
Print
</Button>
</ModalFooter>
</Modal>
</div>
</div>
)
}
)
export default PrintModal
When I open the modal, it gives me the error like this Uncaught TypeError: invalid assignment to const 'componentRef'
Where did I go wrong and how should I fix this?
Try this way, since it is a functional component it should work.
div ref={componentRef}>
/** The content that I want to Print **/
</div
精彩评论