Issue
Let's say I have a navbar and going to render N number of anchor elements inside the navbar based on an array that I have (Type is like [text: string, href: string][])
What would be the best practice of detecting which of those elements are going to be overflowing (in the x axis) from the navbar, so that I can decide to render them somewhere else (like a More Links
dropdown)?
Solution
I add sample code below.
import React, { useEffect, useRef, useState } from 'react';
const Navbar = ({ links }) => {
const navbarRef = useRef(null);
const [overflowLinks, setOverflowLinks] = useState([]);
useEffect(() => {
const navbar = navbarRef.current;
const linksArray = Array.from(navbar.getElementsByTagName('a'));
const navbarWidth = navbar.offsetWidth;
let currentWidth = 0;
const overflowLinksArray = [];
linksArray.forEach((link, index) => {
const linkWidth = link.offsetWidth;
if (currentWidth + linkWidth > navbarWidth) {
overflowLinksArray.push(index);
} else {
currentWidth += linkWidth;
}
});
setOverflowLinks(overflowLinksArray);
}, [links]);
return (
<div>
<div className="navbar" ref={navbarRef}>
{links.map((link, index) => (overflowLinks.indexOf(index) == -1 ?
<a key={index} href={link[1]} style={{color:'green'}}>
{link[0]}
</a> : null
))}
</div>
{overflowLinks.length > 0 && (
<div className="more-links-dropdown">
{overflowLinks.map((index) => {
const link = links[index];
return <a key={index} href={link[1]} style={{color:'red'}}>
{link[0]}
</a>
})}
</div>
)}
</div>
);
};
// Example usage
const App = () => {
const linksArray = [
['Link 1', '/link1'],
['Link 2', '/link2'],
['Link 1', '/link1'],
['Link 2', '/link2'],
['Link 1', '/link1'],
['Link 2', '/link2'],
['Link 1', '/link1'],
['Link 2', '/link2'],
['Link 1', '/link1'],
['Link 2', '/link2'],
['Link 1', '/link1'],
['Link 2', '/link2'],
['Link 1', '/link1'],
['Link 2', '/link2'],
['Link 1', '/link1'],
['Link 2', '/link2'],
['Link 1', '/link1'],
['Link 2', '/link2'],
['Link 1', '/link1'],
['Link 2', '/link2'],
// Add more links as needed
];
return <Navbar links={linksArray} />;
};
export default App;
Answered By - Adrid
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.