티스토리 뷰
소스 코드
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 버튼을 클릭하여 정상적으로 작동하는지 체크해보자.
'프로그래밍 > React' 카테고리의 다른 글
react 리덕스(redux) 기본개념과 사이클(cycle) 구조 알아보기 (1) | 2021.10.01 |
---|---|
ReactJS Tailwind css 사용 방법 (1) | 2021.09.15 |
React map 함수와 key 에 대해서 알아보자 (0) | 2021.09.02 |
React 이벤트 처리에 대해서 알아보자 (0) | 2021.09.02 |
React 컴포넌트 / props / state 에 대해서 알아보자 (1) | 2021.09.01 |
댓글