I want to add the logic of automatically closing an already opened drop-down menu, on opening the other menu. For example, I have opened feature-1 drop down, and while I click on feature-2 to open, feature-1 dropdown should close and vice versa.
const [expand1, setExpand1] = useState(false);
const [expand2, setExpand2] = useState(false);
<ul>
<li>
<div onClick ={() => setExpand1(!expand1)}>
<a onClick={() => openPane('1')} className="menu-item">
<span>Feature-1</span>
<div className={`drop-down ${expand1 ? 'active' : ""}`}>
<i class='bx bx-chevron-down'></i>
</div>
</a>
</div></li>
<li>
<div onClick ={() => setExpand2(!expand2)}>
<a onClick={() => openPane('2')} className="menu-item">
<span>Feature-2</span>
<div className={`drop-down ${expand2 ? 'active' : ""}`}>
<i class='bx bx-chevron-down'></i>
</div>
</a>
</div>
</li>
</ul>
Try adding custom functions as onClick handlers and handle the logic there.
const [expand1, setExpand1] = useState(false);
const [expand2, setExpand2] = useState(false);
const toggle1 = () => {
if(expand2) setExpand2(false)
setExpand1(!expand1)
}
const toggle2 = () => {
if(expand1) setExpand1(false)
setExpand2(!expand2)
}
<ul>
<li>
<div onClick ={toggle1}>
<a onClick={() => openPane('1')} className="menu-item">
<span>Feature-1</span>
<div className={`drop-down ${expand1 ? 'active' : ""}`}>
<i class='bx bx-chevron-down'></i>
</div>
</a>
</div></li>
<li>
<div onClick ={toggle2}>
<a onClick={() => openPane('2')} className="menu-item">
<span>Feature-2</span>
<div className={`drop-down ${expand2 ? 'active' : ""}`}>
<i class='bx bx-chevron-down'></i>
</div>
</a>
</div>
</li>
</ul>
This is very unclean, but demonstrates the general idea.
You can achieve that by using focus and blur. <div> is not automatically focusable, so you need to give it the tabIndex prop to make it focusable.
<div tabIndex="0">
<p>Hello</p>
</div>
Now, the <div> is focusable.
What you need to do next is give the <div> an onFocus and onBlur prop to hide or show the <div>.
const menuRef = React.useRef()
const [focusedIndex, setFocusedIndex] = React.useState(null)
const onFocus = (e, {index}) => setFocusedIndex(index)
const onBlur = (e, {index}) => {
setFocusedIndex(null)
// you can implement your own logic here
}
return (
<div ref={menuRef}>
{
['a', 'b'].map((val, i) => (
<div
onFocus={(e) => onFocus(e, {index: i})}
onBlur={(e) => onBlur(e,{index: i})}
tabIndex="0"
style={{display: focusedIndex === i ? 'block' : 'none'}}
key={`${i}`}
>
<p>Hello</p>
</div>
)
}
</div>
)