Official Solution
import React, { useEffect, useRef, useState } from 'react';
function useOnClickOutside(ref, onOutside) {
useEffect(() => {
function onDown(e) {
const el = ref.current;
if (!el) return;
if (el.contains(e.target)) return;
onOutside();
}
document.addEventListener('mousedown', onDown);
return () => document.removeEventListener('mousedown', onDown);
}, [ref, onOutside]);
}
export default function App() {
const [open, setOpen] = useState(false);
const boxRef = useRef(null);
useOnClickOutside(boxRef, () => setOpen(false));
return (
<div style={{ padding: 16 }}>
<h2 style={{ marginTop: 0 }}>meetcode menu</h2>
<div style={{ position: 'relative', width: 240 }} ref={boxRef}>
<button type='button' onClick={() => setOpen((v) => !v)} style={{ width: '100%', padding: '10px 14px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>Toggle</button>
{open ? (
<div style={{ position: 'absolute', top: 48, left: 0, right: 0, border: '1px solid #eee', borderRadius: 14, background: '#fff', padding: 10, boxShadow: '0 10px 24px rgba(0,0,0,0.08)' }}>
<a href='#' style={{ display: 'block', padding: 8, color: '#124', textDecoration: 'none' }}>Topics</a>
<a href='#' style={{ display: 'block', padding: 8, color: '#124', textDecoration: 'none' }}>Practice</a>
</div>
) : null}
</div>
<div style={{ marginTop: 10, color: '#555' }}>Click outside to close.</div>
</div>
);
}
No comments yet. Start the discussion!