Creating a menu that is even more optimized for mobile devices

I recently came across a mobile menu style that I really like: https://www.w3schools.com/html/default.asp

What I appreciate about this style is that even on smaller screens, it still displays some main navigation items. This allows for popular links to be easily accessible without the need to open the full mobile menu.

Now, I am looking to replicate this behavior using react.

For simplicity's sake, I have created a function that returns all my links through mapping and then renders them 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;
}

The 'cutOffIndex' variable determines how many items should be displayed. As the page width decreases, the cut-off index is reduced to show fewer links.

This method works well, but the issue arises with different link sizes based on text length.

I am seeking a solution that can dynamically calculate each link size to determine how many links can fit within the given width limit.

Initially, I thought of iterating through the links in the constructor and storing their lengths in an array. Then, based on available space, select links that collectively fall under the maximum width.

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

However, this approach seems complex. I am curious if there is a simpler CSS-based solution or a preferred method to achieve this?

Answer №1

To control the visibility of elements based on screen size, you can utilize the 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>
If there is insufficient space in the .left element, the links will wrap to the next line. The use of overflow: hidden ensures that these elements remain hidden.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble installing dependencies in a React project with TypeScript due to conflicts

I encountered a TypeScript conflict issue whenever I tried to install any dependency in my project. Despite attempting various solutions such as updating dependencies, downgrading them, and re-installing by removing node_modules and package-lock.json, the ...

Can you provide a succinct explanation of what constitutes a well-defined "landing page"?

Could someone provide a clear and concise explanation of what exactly constitutes a landing page and how it should be utilized? I'm struggling to grasp the concept. Where is the optimal placement for a landing page on a website? Is it best placed o ...

Encountering an issue while trying to import the validator module in NextJS 13

I encountered a peculiar issue while trying to import a module. Nextjs presented the following error message: ./application/sign_in/sign_in_store.ts:2:0 Module not found: Can't resolve 'validator' 1 | import { createEvent, createStore } fr ...

Retrieve the width of an element once the browser has finalized its dimensions

I am facing an issue with centering a pop-up box perfectly within the window using CSS properties. The code for the pop-up box styling is as follows: #pop_up { position: fixed; display: inline-block; border: 2px solid green; box-shadow: 0p ...

What changes can I make to the script in order to display every element from a MySQL query using PHP, MySQL, JavaScript,

Enhanced Multiple Dropdown Selection Using Ajax In the following scenario, we have a webpage featuring a multiple dropdown selection that interacts with a MySQL database. By choosing options in the dropdowns labeled site, menu, and category (categ), a que ...

Cookie revealed in cookies section, vanishes within a moment [NextJS & cookies-next]

I'm utilizing cookies-next library to create a cookie in my NextJS application, following the documentation provided (pages router, client side): const cookieOptions = { expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 399), // set to expire aft ...

Is the presence of the node_modules folder required in the server for the Next.js production build?

I'm still fairly new to Next.js and its deployment process. Recently, I made the switch from one of my React.js projects to Next.js to take advantage of its server-side rendering feature. However, when it came time to deploy, I realized that the Next ...

What is the best way to toggle the visibility of a component based on a specific width in React JS?

I am trying to toggle my button and it is working, but the issue I am facing is that I want to make it more responsive. I want my sidebar to be closed when the device width is 440 pixels. When we click the button, it should then show. How can I achieve thi ...

The most effective way to code overlapping html buttons

Can you help me figure out how to make clickable areas on my HTML5 web page without them overlapping? Here's what I'm trying to do: I want the red, blue, and green areas to be clickable links, but not overlap. For example, when clicking on the f ...

Optimal ffmpeg configurations for encoding videos into mp4 and ogg formats for seamless playback on HTML5 platforms

Despite the buzz surrounding it, the HTML5 video tag is facing a minor issue. To ensure cross-browser compatibility, multiple video formats - like mp4 and ogg - need to be included for its use. Unfortunately, I couldn't find optimal settings for each ...

What is the best way to align a single item to the right on the navbar in Bootstrap 5.3 (v5.3.0-alpha1)?

Attempting to position a dropdown link to the right in my Bootstrap 5.3 navbar proved to be challenging. The method that worked with Bootstrap 3, using navbar-right, and with Bootstrap 4, possibly ml-auto, did not work with Bootstrap 5 beta which uses me-a ...

What's the best way to loop through each touch event property within the TouchList of a touch event using JavaScript?

I'm struggling to grasp touch events, as nothing seems to be working for me. For testing purposes, I've created a very basic page: HTML: <div id="TOUCHME"> TOUCH ME </div> <div id="OUTPUT"></div> Jav ...

The process of overriding CSS applied through JavaScript

I am using a third-party multi-select dropdown. Similar to Select2, the multi-select dropdown is created using JQuery with select2.min.js and the width of the dropdown is automatically calculated. Is there any way to apply static width to it, as I believe ...

Ways to quickly refresh the user interface following a database modification in next.js

Currently brushing up on my next.js skills and encountering some challenges. I've set up a function called toggleDelete that should be triggered when the delete text is clicked, deleting data from the database. However, the changes aren't immedia ...

What is causing the discrepancy between the appearance of my fiddle and my page?

Hey there, I encountered an issue while working on a page using jsFiddle - it seems to be behaving differently when viewed on the actual website! If you want to take a look: http://jsfiddle.net/8Hpmj/8/ http://ktaadn.me/about/ The example at ktaadn.me do ...

Discover the Next.js App Directory: Automatically refresh the client component when an async function is completed. No need to manually refresh the page for

Seeking assistance with updating a client component in Next.js without a SRC folder and using app router. The component is part of a globally present menu and should update when the user logs in, but currently only refreshes after a browser reload. Various ...

Screen white on the right side

I am encountering an issue where my screen shows white on the side when I scroll to the right. I am unsure how to remove it and cannot locate the problem in the code. Here is a link to the code: https://jsfiddle.net/y3j01hbt/ In the provided code, there i ...

Issue with state not reflecting changes from document snapshots

I am facing a challenge with assigning data to useState by fetching data using reference type value from firebase. const [preOil, setPreOil] = useState([]); const [oilChange, setOilChange] = useState([]); useEffect(() => { getDocs(query(collection(db, ...

When an image is placed inside a parent div, the link should extend to the entire width of the div, rather than just hovering over

Essentially, I have a div that spans the entire width of its container, inside it is an image link. The image's width is set to adjust automatically with a fixed height of 600px. The link covers the whole width of the div, which in this case is the wi ...

Switch ng-model in Angular to something different

I am looking to transform my own tag into a template <div><input .../><strong>text</strong></div> My goal is to have the same values in both inputs. Check out the plunker here If I change the scope from scope: {value:' ...