document.getElementById(“mydiv”) returning null

I am trying to make a div element draggable in react with typescript, following is the code

function dragElement(elmnt:HTMLElement) {
 var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0
 if (document.getElementById(elmnt.id + "header")) {
   document.getElementById(elmnt.id + "header")!.onmousedown = dragMouseDown
 } else {
   elmnt.onmousedown = dragMouseDown;
 }

 function dragMouseDown(e:MouseEvent) {
   e = e || window.event;
   e.preventDefault();
   pos3 = e.clientX;
   pos4 = e.clientY;
   document.onmouseup = closeDragElement;
   document.onmousemove = elementDrag;
 }

function elementDrag(e:MouseEvent) {
  e = e || window.event;
  e.preventDefault();
  pos1 = pos3 - e.clientX;
  pos2 = pos4 - e.clientY;
  pos3 = e.clientX;
  pos4 = e.clientY;
  elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
  elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}

function closeDragElement() {
  document.onmouseup = null;
  document.onmousemove = null;
  }
 }

if (document.getElementById("mydiv") != null) {
dragElement(document.getElementById("mydiv")!);
}

  export const PopUpCommon= () =>{ 
    return(
    <div id="mydiv">
    <div id="mydivheader">Click here to move</div>
    <p>Move</p>
    <p>this</p>
    <p>DIV</p>
  </div> 
  )}

Here I am checking document.getElementById(“mydiv”) is null or not to avoid the console error ‘Cannot read properties of null (reading ‘id’)’, since that is returning null dragElement is not getting called. Why is that returning null even if an element with the id “mydiv” is present ?