티스토리 뷰

소스 코드

useState를 이용하여, toggle 기능을 쉽게 구현할 수 있으니 참고하자.

핵심은 onClickGnb 호출 시, 이전 상태를 삼항연산자로 처리하면 쉽게 구현할 수 있다.

 

const [gnbStatus, setGnbStatus] = useState(false);

const onClickGnb = (e) => {
    setGnbStatus(prevStatus => prevStatus ? false : true);
  };

const GnbMenu = () => (
    <div id="gnbMenu" class="pt-4 pb-8">
      <div class="flex flex-col w-full mx-auto px-4">
        <div class="flex flex-col space-y-2 text-gray-500">
          <a class="hover:underline menu-item-root" href="/1">메뉴1</a>
          <a class="hover:underline menu-item-root" href="/2">메뉴2</a>
          <a class="hover:underline menu-item-root" href="/3">메뉴3</a>
        </div>
      </div>
    </div>
  );
  
  
  ... 생략 ...
  
  
  <header>
  <div className="inline-block absolute py-1 right-2 cursor-pointer" onClick={onClickGnb}>
  	<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-menu"><line x1="3" y1="12" x2="21" y2="12"></line><line x1="3" y1="6" x2="21" y2="6"></line><line x1="3" y1="18" x2="21" y2="18"></line></svg>
  </div>
  </header>

{/* Gnb Menu */}
{ gnbStatus ? <GnbMenu /> : null}

 

 

 

출력 결과

gnb 버튼을 클릭하여 정상적으로 작동하는지 체크해보자.

 

gnb - 클릭 전

 

 

gnb - 클릭 후

 

댓글