title: reactJS - Adding an event handler to an element which might, or might not exist at this time
body: <p>I am not allowed to answer questions yet, but I feel that since this issue has taken me some days to resolve, I should post the solution the only way I can - as a question.</p>
  
  <p>If you have a better solution then please include that in your reply.</p>
  
  <p>Until an element is rendered it is not in the DOM so if you add an event listener to the element in your code you will get an error (element value null).</p>
  
  <p>But you can add a listener to the root element, which is always there.  WHen the event is triggered you can then retrieve the className and ID of the element involved in your event-handler.</p>
  
  <p>Code:</p>
  
  <pre><code>     var rootElement = document.getElementById('root'); 
       console.log(rootElement);
       rootElement.addEventListener('click', rootElementClicked);
  
      console.log('event listener added to root element');
  
      function rootElementClicked(event) {
        event.preventDefault();
        const { name, value } = event.target;
  
        console.log("Root element clicked with [" + event.target.className, event.target.id);
      }
  </code></pre>
  
  <p>/code
  So, the event-listener is app-wide, so a click anywhere will call the event-handler function.  Then in the code for that function, the element class and ID will tell you what was clicked.</p>
  
  <p>Note the event.preventDefault(); line - it prevents a refresh of the web page, otherwise the target class &amp; ID are returned as "undefined"</p>