본문 바로가기
TIL/TIL

kakaomap : Cannot read properties of null(reading 'currentStyle')

by 안뇽! 2022. 11. 19.
반응형

카카오지도 에러 : Cannot read properties of null(reading 'currentStyle')

 

카카오지도 공식문서에는 다음과 같이 가이드를 주고 있다.

<script>
		var container = document.getElementById('map');
		var options = {
			center: new kakao.maps.LatLng(33.450701, 126.570667),
			level: 3
		};

		var map = new kakao.maps.Map(container, options);
 </script>

 

이를 리액트로 변환시켜 다음과 같이 작성하였다.

 

document로 id를 찾아 참조하지 않고 ref를 사용하였다.

import { useRef } from 'react';
import styles from './mappage.module.scss';

const MapPage = () => {
  const mapRef = useRef(null);

  const container = mapRef.current;

  const options = {
    center: new window.kakao.maps.LatLng(37.17058840207, 127.112843761156),
    level: 2
  };
  const map = new window.kakao.maps.Map(container, options);

  return (
    <section className={styles.wrapper}>
      <article ref={mapRef} className={styles.map} id={styles.map}></article>
    </section>
  );
};

export default MapPage;

 

그러자 다음과 같은 에러가 나타난다.

 

카카오 개발자 홈페이지에 달린 답변에 의하면 돔 트리 구성때 카카오 지도를 넣을 <div id = 'map'>가 생성되지 않은 상태에서 #map을 참조하기 때문이다.

 

useEffect

useEffect는 DOM 렌더링이 완료된 이후에 실행되는 훅이다.

 

useEffect안에 카카오지도 관련된 모든것을 넣어주면 <div id = 'map'>이 생성된 이후에 #map을 참조하게 될 것이다.

 

import { useEffect, useRef } from 'react';
import styles from './mappage.module.scss';

const MapPage = () => {
  const mapRef = useRef(null);

  useEffect(() => {
    const container = mapRef.current;

    const options = {
      center: new window.kakao.maps.LatLng(37.17058840207, 127.112843761156),
      level: 2
    };
    const map = new window.kakao.maps.Map(container, options);
  }, []);
  return (
    <section className={styles.wrapper}>
      <article ref={mapRef} className={styles.map} id={styles.map}></article>
    </section>
  );
};

export default MapPage;

useEffect에 카카오지도 관련된 로직을 넣어주니 지도가 잘 생성된다.

반응형