๐Ÿค ์€์ง€log ๐Ÿค

[REACT] DropDown ๋ณธ๋ฌธ

๐Ÿ’™ React

[REACT] DropDown

Eun_zii 2022. 10. 6. 13:40

๐ŸŽฃ 1. Bootstrap.jsx ์ปดํฌ๋„ŒํŠธ ์ƒ์„ฑ

import Dropdown from './Dropdown'

const Bootstrap = () => {
  return (
    <div>
      <Dropdown />
    </div>
  )
}
export default Bootstrap

๐ŸŽฃ 2. Dropdown.jsx ์ปดํฌ๋„ŒํŠธ ์ƒ์„ฑ

import { useEffect, useState, useRef } from 'react'
import styled from 'styled-components'

const Dropdown = () => {
  const [showList, setShowList] = useState(false)
  const btnEl = useRef(null)

  useEffect(() => {
    const onClick = (e) => {
      if (btnEl.current !== e.target) setShowList(false)
    }
    document.body.addEventListener('click', onClick)
    return () => {
      document.body.removeEventListener('click', onClick)
    }
  }, [])

  return (
    <Wrapper>
      <Button ref={btnEl} onClick={() => setShowList(!showList)}>
        Dropdown
      </Button>
      {showList && (
        <List>
          <Item>Item #1</Item>
          <Item>Item #2</Item>
          <Item>Item #3</Item>
          <Item>Item #4</Item>
        </List>
      )}
    </Wrapper>
  )
}

const Wrapper = styled.div`
  position: relative;
`
const Button = styled.button``
const List = styled.ul`
  list-style: none;
  margin: 0;
  padding: 0;
  background: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  min-width: 200px;
  position: absolute;
`
const Item = styled.li`
  padding: 5px 15px;
  & + & {
    border-top: 1px solid #ddd;
  }
  :hover {
    background: #efefef;
  }
`

export default Dropdown

 

โญ๏ธ

  • Drop down ์„ ์—ด๊ณ  drop down ์„ ์ œ์™ธํ•œ ๋ถ€๋ถ„์„ ํด๋ฆญํ–ˆ์„๋•Œ (body๋ผ๋˜๊ฐ€..) drop down์ด ๋‹ซํžˆ๊ณ  ( ๋‹ซํžŒ๋‹ค๋Š” ๊ฒƒ์€ drop down ๋‚ด์— show List๊ฐ€ false๊ฐ€ ๋˜๋Š”๊ฒƒ )
  • false๊ฐ€ ๋˜๋ ค๋ฉด ์ „์ฒด body์— Event Listener๋ฅผ ๋ถ™์—ฌ์„œ body๊ฐ€ ํด๋ฆญ๋ ๋•Œ๋งˆ๋‹ค false๋ฅผ ๋งŒ๋“œ๋Š”๊ฒƒ. ํ•˜์ง€๋งŒ Btn๋„ body๋ผ์„œ ์ ˆ๋Œ€ true๊ฐ€ ๋ ์ˆ˜์—†๋‹ค. ๊ทธ๋ž˜์„œ btn๊ณผ ํด๋ฆญํ•œ target์„ ๋น„๊ตํ•ด์„œ btn์„ ๋ˆ„๋ฅธ์ƒํ™ฉ์ด๋ฉด show List๋ฅผ false๋กœ ๋งŒ๋“ค์ง€ ์•Š๋Š”๊ฒƒ.
  • body์— remove Event Listener๋ฅผ ๋ถ™์ด์ง€ ์•Š์œผ๋ฉด console.log๊ฐ€ ์—ฌ๋Ÿฌ๋ฒˆ ์ฐํžˆ๊ฒŒ ๋˜๋‹ˆ remove๋ฅผ ๋ถ™์ด๋Š”๊ฒŒ ์ข‹๋‹ค.

โญ๏ธ

 

728x90

'๐Ÿ’™ React' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[REACT] Instagram _ Log-In  (0) 2022.10.06
[REACT] Naver ์ฑ… ๊ฒ€์ƒ‰  (0) 2022.10.06
[REACT] Naver ์˜ํ™” ๊ฒ€์ƒ‰  (0) 2022.10.06
[REACT] Modal  (0) 2022.10.06
[REACT] Accordion  (0) 2022.10.06