React - UseRef를 이용한 조작.

samuel Jo·2023년 6월 7일
0

react

목록 보기
2/2

웹을 보다 보면 특정 버튼 ex)로그인 모달이 나왔을때 끄고 싶은 경우 x 버튼을 누르는것 외에 다른 영역을 클릭시 모달이 꺼지는 기능을 쉽게 볼 수 있는데,

이를 어떻게 구현해야 하는지 찾아봤고, 직접 작성 해봤다.

UseRef라는걸 사용하면 되는데, UseRef가 무엇인가?!

UseRef

다음은 내가 연습해본 코드다.
작성한 코드는 React 환경에서 작성했고, 코드에 대한 설명은 주석을 통해 달았다.(내가 나중에 보고 쓰기 편하게끔.)

import React, { useRef } from 'react';
import { useState, useEffect } from 'react';
import styled from 'styled-components';
const Filter = ({ handleFilter }) => {
    /**드롭다운 */
    const [isOpen, setIsOpen] = useState(false);
    const [selectedOption, setSelectedOption] = useState("전체");
    const dropdownRef = useRef(null);
    const toggleDropdown = () => {
        setIsOpen(!isOpen);
    };
    /**드롭다운 밖에 클릭했을때 드롭다운 리스트 없애기 */
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
                setIsOpen(false);
            }
        };

        document.addEventListener('click', handleClickOutside);
        return () => {
            document.removeEventListener('click', handleClickOutside);
        };
    }, []);




    /**filter창 열었을때 */
    const handleOptionClick = (option) => {
        setSelectedOption(option);
        handleFilter(option);
        setIsOpen(false);
    };



    /**region을 배열로 두고 map으로 뽑아쓰기. */
    const continents = ['전체', '아프리카', '유럽', '아시아', '오세아니아', '아메리카'];

    return (
        <Dropdown ref={dropdownRef}>
            <Button onClick={toggleDropdown}>{selectedOption}</Button>
            <Menu isOpen={isOpen}>
                {continents.map((continent) => (
                    <MenuItem key={continent} onClick={() => handleOptionClick(continent)}>
                        {continent}
                    </MenuItem>
                ))}
            </Menu>
        </Dropdown>
    );
};

export default Filter;


const Dropdown = styled.div`
  position: relative;
  display: inline-block;
`;

const Button = styled.button`
  padding: 10px;
  background-color: #f5f5f5;
  border: none;
  outline: none;
  cursor: pointer;
`;

const Menu = styled.ul`
  position: absolute;
  top: 100%;
  left: 0;
  width: 200px;
  padding: 0;
  margin: 0;
  background-color: #fff;
  border: 1px solid #ccc;
  list-style-type: none;
  display: ${({ isOpen }) => (isOpen ? 'block' : 'none')};
`;

const MenuItem = styled.li`
  padding: 8px;
  cursor: pointer;

  &:hover {
    background-color: #f2f2f2;
  }
`;
profile
step by step

0개의 댓글