[ERR] Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element | DocumentFragment'. Type 'null' is not assignable to type 'Element | DocumentFragment'. 해결하기

🍒Jooooooo_eun🍒·2023년 4월 10일
0
Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element | DocumentFragment'.
  Type 'null' is not assignable to type 'Element | DocumentFragment'. 

ReactDOM.createPotal 사용 시 해당 에러가 뜨면서 document.getElementById 를 읽지못했다.
해당 에러를 수정하려면 ! 를 붙여주면 된다
타입스크립트는 document.getElementById("modal-root") 가 null 일 수 있다고 생각하기때문에 발생하는 오류기 때문에 null 이 아님을 주장해주면 간단하게 해결이 가능하다. 이 외에도 해당 dom 을 사용하는 에러들은 ! 로 해결이 가능하다

👉 변경전

	  <div>
        {ReactDOM.createPortal(
          <HomeModal />,
          document.getElementById("modal-root") // 에러 발생
        )}
      </div>

👉 변경후

	  <div>
        {ReactDOM.createPortal(
          <HomeModal />,
          document.getElementById("modal-root")! // 에러 수정
        )}
      </div>

참고

https://stackoverflow.com/questions/69007457/createportal-typescript-document-getelementbyid-type-issue-when-javascript-run

profile
먹은만큼 성장하고 싶은 초보 개발자의 끄적끄적 개발메모장 ✍

0개의 댓글