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

Show or hide the expand/collapse button based on the height of the container

Looking for a way to hide content in a Div if it's taller than 68px and display an expand option? The challenge lies in detecting the height of the responsive Div, especially since character count varies. I attempted using PHP to count characters bu ...

Creating full-width divs using BootstrapLearn how to easily create full-width div

Bootstrap is being utilized in my current project. I have been creating divs inside columns, but they are not extending to the full width of the columns. Below is a snippet of the code: <!DOCTYPE html> <html lang="en"> <head> ...

Notification of Exceeding File Size Limit

Seeking assistance with implementing a 'filesize' error message into a script used for uploading BLOB files to a mySQL server. if (!mysql_connect($db_host, $db_user, $db_pwd)) die("Can't connect to database"); if (!mysql_select_db($dat ...

Is there a way to use jquery and ajax to swap out an image on a webpage when a button is clicked?

I am trying to create a button on my HTML page that, when clicked, will asynchronously change a specific image on the page. Here's what I have so far: <a href="/test/page"> button </a> What I want is for the button click to change this i ...

links contained within a single span inside an anchor tag

I am attempting to place all three spans within an anchor tag, inline. I am not certain what is missing from the code: a.facebook-button { float: none; display: inline-block; margin-bottom: 5px; left: auto; text-shadow: 0 -1px 1px rgba(0, 0, 0 ...

Issue with background image resizing when touched on mobile Chrome due to background-size property set to cover

My current challenge involves setting a background image for a mobile page using a new image specifically designed for mobile devices. The image is set with the property background-size: cover, and it works perfectly on all platforms except for mobile Chro ...

best practices for creating space between flexbox items

My task involves presenting a continuous scroll list of scheduled jobs using Angular Material. Each item in the list needs to be divided into three columns utilizing flexbox. Despite my efforts, I am struggling with adding space between the columns within ...

Nextjs style import function properly on the development server, but faces issues when deployed to production environments

import "../styles.css"; import styles from "react-responsive-carousel/lib/styles/carousel.min.css"; import "react-owl-carousel2/lib/styles.css"; import { Provider } from "react-redux"; import store from "../store/store" function App({ Component, pageProps ...

"The Node.js program is unable to access the contents of the browser.js file when loaded in

After spending an unreasonable amount of time trying to debug this issue, I am still unable to resolve it. Currently, I am following a udemy tutorial where the instructor implements the same code provided below. However, despite my efforts, the code is not ...

Container A running a React app is experiencing difficulties retrieving data from Container B hosting an ExpressJS server within the shared Docker network

I have encountered an issue with my setup involving two containers. One container is hosting a React app within an NGINX image, while the other container is running a NodeJS Express app. Both containers are connected on the same Docker network. https://i. ...

Retrieve information from slider upon completion of dragging action while state is being modified within React.js

One of the challenges I am facing involves a slider that updates the values of a state variable: handleSliderChange = (event, value) => { this.setState({sliderValue: value,}); }; fetchDataOnDragEnd = (event, value) => { this.props.fetchData ...

Is there a way to adjust the height of a DIV based on the background image and keep the text centered at the same time?

Currently in the process of designing a landing page for my website, and I am interested in incorporating a Jumbotron to provide a more modern and tech-savvy touch. Successfully managed to center my text both horizontally and vertically, now looking into s ...

Would ReactJS (or NextJS) be a good fit for a traditional website?

Would using reactjs (or nextjs) be a suitable choice for creating a classic website? I am planning to develop a website for a kindergarten. Is it a good or bad idea to proceed with using react, considering it will be a multiple page app? Or would it be bet ...

Having trouble showing images from block content using PortableText?

It's been quite a while now that I've been stuck on this issue. Despite being in a learning phase, I find myself unable to progress due to this specific problem. While links and text elements are functioning properly, I have encountered difficul ...

How to properly handle file uploads and get the correct image path from Node Js (Express) to React Js?

Currently, I am working on my local system developing a file upload feature using node js. My project file structure looks like this: Project ..client .... source code of React App ..Server ....uploads ......avatar ........image.png ....index.js In this ...

Having difficulty displaying this code accurately on Google Chrome

I managed to create a hover effect over a series of images that displays additional information when hovered over. Below is the code I used: HTML <ul class="photo-grid"> <li> <a href="https://www.abglobal.com/" target="_blank"& ...

React component making repeated calls to my backend server

As a React newbie, I am currently in the process of learning and exploring the framework. I recently attempted to fetch a new Post using axios. However, upon hitting the '/getPost' URL, I noticed that the GetPost component continuously calls the ...

How do I directly display a variable in index.html using node.js?

Is there a way to retrieve user inputs from the index.html file, process them in Node.js, and then display the result back on the index.html page instead of redirecting to a new page? Form Handling with Express var express = require('express'); ...

CombineReducers takes all the reducer content and unpacks it into a single reducer

As I work on developing a small application, I am contemplating the best strategy for organizing reducers within it. My objective is to retrieve JSON data from the application state and structure it as shown below: { "fruits": [ {"appl ...

Creating a container component that has access to the values of its children: a step-by-step guide

I've designed a component wrapper that looks like this: <SpecialWrapper config={}> {this.props.children} </SpecialWrapper> The intention is to utilize it in the following manner: <SpecialWrapper> // whatever other c ...