css, 상태 변경을 통해서 구현코드
// 모달을 열고 닫는 상태를 관리
const [modalStates, setModalStates] = useState({});
// 모달을 열고 닫는 함수 : id를 가지고 해당 id의 모달 상태를 열고 닫음
const toggleModal = (shopId) => {
setModalStates((prevStates) => ({
...prevStates,
[shopId]: !prevStates[shopId]
}));
};
// 상위 컴포넌트 => 하위 컴포넌트 이벤트 전파를 막는 함수
const stopBubble = (e) => {
e.stopPropagation();
e.preventDefault();
};
// 조건부 렌더링
{modalStates[shop.id] && (
<ModalOverlay onClick={() => toggleModal(shop.id)}>
<ModalContent onClick={stopBubble}>
<CloseButton type="button" onClick={() => toggleModal(shop.id)}>
X
</CloseButton>
<Detail shop={shop} />
</ModalContent>
</ModalOverlay>
)}

// 데이터 베이스에서 비동기적으로 api를 불러옴
// restaurants 테이블에서 전부(*) 가져오는데 평점(rating) 순 내림차순(ascending: false)으로 불러오기
const fetchRestaurants = async () => {
const { data } = await supabase.from('restaurants').select('*').order(`rating`, { ascending: false });
return data;
};
이번 프로젝트 간 알아두면 유용하고 실무에서도 자주 쓰일 법한 조건부 렌더링에 대해서
구글링해서 찾아보고 구현을 해봤다.
&& 연산자 : 논리 AND 연산자
구현 코드
// modalStates[shop.id]의 상태에 따라 조건부 렌더링
{modalStates[shop.id] && (
<ModalOverlay onClick={() => toggleModal(shop.id)}>
<ModalContent onClick={stopBubble}>
<CloseButton type="button" onClick={() => toggleModal(shop.id)}>
X
</CloseButton>
<Detail shop={shop} />
</ModalContent>
</ModalOverlay>
)}
동작 과정
1. 조건 확인 : modalStates[shop.id]가 true
2. 평가 및 렌더링
할게 많다..!