버튼을 누르면 모달(Modal)을 띄우고 그 모달안에 리스트가 있는 형태이다.
먼저 import
import React, { useState, useEffect } from 'react';
import styled from "styled-components";
버튼과 모달이 될 div, 그리고 모달 안에 들어갈 리스트 아이템을 생성했다. 리스트의 경우는 ul 과 li를 써도 되고 편의에 따라서 div로 바꿔도 된다. 추후에 나는 div로 바꿨다.
const Button = styled.button`
  background-color: #5633EC;
  color: #FFFFFF;
  border: none;
  border-radius: 10px;
  font-size: 16px;
  height: 50px;
  width: 200px;
  margin-top: 20px;
  cursor: pointer;
`
const Modal = styled.div`
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 500px;
  height: 308px;
  background-color: #F2F4F6;
  border-radius: 20px;
  padding: 20px;
`
const List = styled.ul`
  list-style: none;
  margin: 0;
  padding: 0;
`
const ListItem = styled.li`
  margin-top: 20px;
  font-size: 18px;
  cursor: pointer;
`
본격적으로 모달 띄우는 코드
const ModalPage = () => {
  const [selectedOption, setSelectedOption] = useState('');
  const [showModal, setShowModal] = useState(false);
  
  //모달안에 들어갈 리스트 아이템 내용
  const fruits = ['사과', '바나나', '귤'];
//버튼 누를 때 바뀌는 값에 따라서 modal 보이기 여부
  useEffect(() => {
    document.body.style.overflow = showModal ? 'hidden' : 'initial';
  }, [showModal]);
//버튼 누를 때 값 변경
  const handleOptionClick = (option) => {
    setSelectedOption(option);
    setShowModal(false);
  };
  return (
    <>
      <Button onClick={() => setShowModal(true)}>
        {selectedOption ? selectedOption : 'Click me to open modal'}
      </Button>
      
      {showModal && (
        <Modal>
          <List>
            {fruits.map((option) => (
              <ListItem onClick={() => handleOptionClick(option)} key={option}>
                {option}
              </ListItem>
            ))}
          </List>
        </Modal>
      )}
      
    </>
  );
};
export default ModalPage;
이후에 모달 배경 흐리게 하는 부분과 모달 내부가 스크롤이 되어야 했는데 좀 더 정리 후에 써야겠다.
'개발 공부 > Next.js' 카테고리의 다른 글
| [Next.js/JS] cookies-next이용해서 쿠키 생성하기 (0) | 2023.02.27 | 
|---|---|
| [Next.js/JS] : Local JSON 파일 읽어서 dynamic route에서 출력하기 (0) | 2023.02.22 | 
| [Next.js/JS] 클릭하면 상태 변하는 이미지 버튼 만들기(styled-components) (0) | 2023.02.21 | 
| [Next.js/JS] next-auth session 상태에 따라 화면 전환하기 (0) | 2023.02.06 | 



