๐ค ์์งlog ๐ค
[REACT] DropDown ๋ณธ๋ฌธ
๐ฃ 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 |