0

I'm trying to print the content of a function in react but getting Uncaught TypeError: Cannot read property 'innerHTML' of null

function:

export default function Home(props) {
    return (
       <h4>Some other contents</h4>
       <button className='btn' type='button' onClick={printDiv('printMe')}>Print</button>
   )
}

function Data(props) {
   return (
   <div id='printMe'>
      <p>Some contents in here returning from my database</p>
      <p>On an html table</p>
   </div>
  )
}

function printDiv(divName) {
  let printContents = document.getElementById(divName).innerHTML;
  let originalContents = document.body.innerHTML;

  document.body.innerHTML = printContents;

  window.print();

  document.body.innerHTML = originalContents;
}

So far, once the application is loaded I get the error. I'm not sure what's causing the issues.

2
  • The value of onClick has to be a function; what happens if you pass a function? Like onClick={() => printDiv('printMe')}. Commented Nov 30, 2017 at 21:28
  • This works. Really helpful, thanks.. Commented Nov 30, 2017 at 21:53

1 Answer 1

1

I assume this script is located inside your <head> tag. Are you running your code after the page loads?

If you want to access the DOM, you need to make sure that the DOM element(s) you're trying to access actually exist.

Try doing this on the script tag:

<script src="path/to/your/script.js" defer></script>

The defer attribute makes it run after the page finishes loading; hence, it'll have proper access to the DOM.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.