Building a 'more' mobile responsive menu

Viewed 60

I am a big fan of this particular style of mobile menu: https://www.w3schools.com/html/default.asp

Reason being even on mobile layouts, depending on the size of the page, it still shows some main navigation items. That way I think you could perhaps show some of your most popular links, without the user having to go into the mobile menu.

I am trying to recreate this behavior with react.

To keep the example simple: I return all my links from a map statement and render it in the layout:

getNavigationItems(){
    const items = this.props.routes.slice(0, this.state.cutOffIndex).map((link) =>
    <a 
        className="DNavigationContainer-LinkItem"
        href="#"
        >{link.title}</a>
    );
    return items;
}

That 'cutOffIndex' is used to determine if I should only be showing a subset of items. As my page width gets smaller, I decrement the cutoff index to show less and less.

That works well, the only issue is some of these links are different sized (based off the amount of text).

I need a solution that would understand how big each link is, therefore I understand how many links I can show without being over the width.

I thought about in the constructor of my element looping through each link and storing the size in an array, and then recalling that array (when say I have 300 pixels to work with, get as many elements that I can that would be shorter than 300 pixels combined).

for(var i = 0; i < this.props.routes.length; i++){
    var textLength = this.props.routes[i].title.length;
    //store this text length in an array?
}

However, this seems overcomplicated, and I wonder if there is a simplier way to do this in CSS? Or a prefered approach?

1 Answers

You can hide elements based on screen size with CSS property overflow: hidden.

nav {
  width: 100%;  
  border: 1px solid #000;
}

a {
  display: inline-block;
  height: 30px;
  background: #fff;
  padding: 5px 15px;
  box-sizing: border-box;
}

.left {  
  overflow: hidden;
  height: 30px;
}

.right {
  overflow: hidden;
  float: right;
}
<nav>
  <div class="right">
    <a href="#">Always visible</a>
  </div>
  <div class="left">    
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
    <a href="#">Link 4</a>
    <a href="#">Link 5</a>
    <a href="#">Link 6</a>
    <a href="#">Link 7</a>
    <a href="#">Link 8</a>
    <a href="#">Link 9</a>
    <a href="#">Link 10</a>
    <a href="#">Link 11</a>
    <a href="#">Link 12</a>
  </div>
</nav>
When there is not enough space in .left element, links will be wrapped to the next line. Property overflow: hidden ensure that those elements are not visible.

Fiddle: https://jsfiddle.net/ojgbvq5c/

Related