React: I have a menu and list of sub menus. I want to calculate the sub menus count and if it exceed from 3, rest sub menus will be hide.
Code for try count the elements
export default function App() {
const ElementRef = useRef(null)
useEffect(() => {
const Elementcount = ElementRef.current.childNodes.length;
console.log(Elementcount);
})
return (
<div className="menus" ref={ElementRef}>
<div className="submenus">
<div>Menu 1</div>
<div>Menu 2</div>
<div>Menu 3</div>
// Menu 4 & 5 hide
<div>Menu 4</div>
<div>Menu 5</div>
</div>
<div className="submenus">
<div>Menu 1</div>
<div>Menu 2</div>
<div>Menu 3</div>
// Menu 4 hide
<div>Menu 4</div>
</div>
</div>
)
}
CodePudding user response:
why not with CSS ? There should be a better one, but this works
.submenus > div{
display: none /* hide all */
}
.submenus > div:nth-child(-n 3) {
display: block /* show first three */
}
<div className="menus">
<div >
<div>Menu 1</div>
<div>Menu 2</div>
<div>Menu 3</div>
<div>Menu 4</div>
<div>Menu 5</div>
</div>
<hr/>
<div >
<div>Menu 1</div>
<div>Menu 2</div>
<div>Menu 3</div>
<div>Menu 4</div>
</div>
</div>
CodePudding user response:
const menus = [{name: "menu1"}, {name: "menu2"}, {name: "menu3"}, {name: "menu4"}]
{menus.map((menu, index) => index < 3 ? <div>{menu.name}</div> : null)}