Tips for ensuring that Breadcrumbs are displayed properly with the noWrap feature

I am currently working on making the MUI component Breadcrumbs responsive.

The issue I am facing is that when the Breadcrumbs component fills up all available space, the items shrink and use ellipsis like a Typography component with the noWrap property set.

While I am aware of the itemsBeforeCollapse, itemsAfterCollapse, and maxItems props, these properties are related to the number of items compared to viewport size rather than the width of each individual item.

I have attempted setting the noWrap property on both the Typography and Link components (since Link extends Typography props), but unfortunately the ellipsis does not display and the Link or Typography component does not shrink as expected.

<Breadcrumbs>
  {links.map((link, i) =>
    i !== links.length - 1 ? (
      <Link
        key={i}
        underline={'hover'}
        noWrap
      >
        {link}
      </Link>
    ) : (
      <Typography noWrap key={i}>
        {link}
      </Typography>
    ),
  )}
</Breadcrumbs>

If you want to see the issue in action, you can view this codeSandbox:

https://codesandbox.io/s/basicbreadcrumbs-material-demo-forked-vio1d?fontsize=14&hidenavigation=1&theme=dark

Answer №1

It seems like the issue you're facing is that the noWrap style isn't affecting the correct element.

But why is this happening?

The noWrap style only affects elements with a width limitation, either explicitly set (e.g. width: 100px) or implicitly by its parent's width.

In your scenario, the Link and the Typography elements do not have limited widths.

So what can you do to fix it?

When Breadcrumbs renders an ol with display: flex, you can make the children (li) stand in a line and take up space by assigning them flex: 1. Then, you can apply ellipsis styles to the li elements.

How do you achieve this? There are multiple methods outlined in the CSS section.

I suggest using the styled approach, which would look something like this:

// JavaScript code snippet here...

Check out this CodeSandbox link for a demo.

Answer №2

Here is the solution I came up with. Please focus on the StyledBreadcrumbs and sx within the <Breadcrumbs>.

This code reduces the size of all items except the last one. If you want to reduce the size of the last item, simply delete :not(:last-of-type) from one of the style selectors.

import type { ReactElement } from 'react';
import type { BreadcrumbsProps } from '@mui/material';

import React, { MouseEventHandler } from 'react';
import { Link, Breadcrumbs as MUIBreadcrumbs, Typography, styled } from '@mui/material';

const StyledBreadcrumbs = styled(MUIBreadcrumbs)({
    maxWidth: '100%',
    '.MuiBreadcrumbs-ol': {
        flexWrap: 'nowrap'
    },
    '.MuiBreadcrumbs-separator': {
        flexShrink: 0
    },
    '.MuiBreadcrumbs-li:not(:last-of-type)': {
        overflow: 'hidden'
    }
});

export type Breadcrumb = {
    text: React.ReactNode;
    href?: string;
    onClick?: MouseEventHandler<HTMLAnchorElement>;
};

type Props = {
    breadcrumbs: Breadcrumb[];
} & Omit<BreadcrumbsProps, 'children'>;

export function Breadcrumbs({ breadcrumbs, ...props }: Props): ReactElement {
    return <StyledBreadcrumbs {...props}>
        {breadcrumbs.map(({ text, href, onClick }, index) => {

            const sx = index === breadcrumbs.length - 1 ? {} : {
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap'
            };

            if (href || onClick) {
                return (
                    <Link key={index} color='inherit' href={href} onClick={onClick} sx={sx}>
                        {text}
                    </Link>
                );
            }

            return (
                <Typography key={index} color='inherit' sx={sx}>
                    {text}
                </Typography>
            );
        })}
    </StyledBreadcrumbs>;
}

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

Creating a responsive Material UI Container Component is imperative for ensuring a user

Is there a way to have the Container Component with a maxWidth Prop that changes based on Theme Breakpoints? If not, what is the best approach to achieve this functionality? ...

Conceal the content within the body and reveal a uniquely crafted div element using Print CSS

I came across numerous resources on using CSS to hide specific parts of a webpage. However, I am not looking to hide multiple divs like this: #flash,#menu,#anuncios { display:none; } Instead, my goal is to hide the entire body of the page and only displ ...

What is the best way to conceal padding designated for invisible scrollbars?

I am facing a perplexing problem with a nav element that always shows an empty scrollbar area, even when it is not required. Here is how it looks with all content displayed: https://i.stack.imgur.com/PzeiP.png This is how it appears when the window heigh ...

Issue: Invalid element type - Error message displayed when attempting to show the Edit button

I am currently learning about React and trying to implement an edit button next to the rows for editing data in the database. However, I keep encountering this specific error message: Error: Element type is invalid: expected a string (for built-in compone ...

What is the best way to make Bootstrap 3 move to a new line when there is not enough space?

I am facing an issue with a lengthy text inside a div with a class of "col-md-3". The text is so long that it appears to be overlapping with the content of another div. Adding spaces is not an option as it is an email address, and it displays fine on some ...

Switching Themes in Material-UI Version 5: Facing Compilation Issues While Importing Styles

Currently facing an issue with using the Material UI custom theme, resulting in errors with style components. Despite having already installed npm packages like "@mui/material", "@emotion/react" and "@emotion/styled", the error persists. My project utilize ...

Feeling puzzled by the concept of CSS Block Formatting Contexts (BFCs)

In the World Wide Web Consortium (W3C), the concept of Block Formatting Context (BFC) is explained as follows: Within a block formatting context, boxes are arranged one after another in a vertical manner, starting at the top of a containing block. The dist ...

Incorporate a dropdown menu based on the selection made in another dropdown menu

I have a scenario on my website where I want to dynamically add select boxes based on the value selected in the previous one. Here is the code snippet: <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.js"> </script> & ...

Problems with implementing media queries in CSS

Our team is currently delving into the realm of responsive design and experimenting with a mobile-first framework. In an attempt to utilize media queries to adjust our layout based on screen size, we have crafted the following CSS: .flex, .cards, .card { ...

Enhance your title bar with an eye-catching image

Is there a way to add an image to the title bar? I currently have the title set as "Webnet". I attempted to combine it with a FontAwesome Glyphicon's icon image like this: <title><i class="icon-user icon-black"></i>Webnet</titl ...

Achieving left text alignment in CSS for an excerpt using the Ultimate Posts Widget on Wordpress

I've been trying to align the text in the excerpt of a widget called "To-Do List" on the left sidebar. I attempted to set the text-align property to left for the excerpt text, targeting the p tag within the .widget_ultimate_posts, .uw posts using CSS ...

Adjust the initial slider according to the values displayed in the following four sliders

Having an issue updating the slider value in the first one based on selected values from four other sliders. The selected value should not exceed 50, which is the maximum value in the first slider. Link to Working Fiddle : Below is the HTML code : & ...

Guide to displaying a progress bar while submitting a form using JavaScript and AJAX

After successfully creating the progress bar for my project, I encountered a technical issue. When I choose to upload a file, it gets uploaded twice - once when selecting the file and then again when submitting the form. This creates a poor user experience ...

Methods to modify the state of a Modal component beyond the boundaries of a React class

I am attempting to trigger my modal by modifying the state from outside of the react class. Unfortunately, I have had no success thus far. I have experimented with the following approach: In my code, I have a method named "Portfolio" that is responsible f ...

Error with React, key must be unique. What's the issue?

What is causing the issue with unique keys? To resolve the problem, ensure that each list item has a unique key. For example, if we have x_values = {'male':[1,2,3], 'female':[2,3,4]} the keys should be : 'mean-male', ' ...

What is the best way to create an impact?

Need help fixing the parallax effect on this page. I attempted to implement a parallax effect but encountered some issues. Here is the JavaScript code: $objWindow = $(window); $('section[data-type="background"]').each(function(){ var $bgOb ...

Characters from Font Awesome are invisible on my screen

I am struggling with the font awesome plugin as I am unable to view the characters. Below is my code snippet: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <l ...

Adjust the size of a menu by modifying its width

Hey everyone, I recently joined this website and I'm still learning how to code. My current project involves creating an off-canvas menu, but I've come across a few challenges. Firstly, does anyone know how to adjust the width of the menu when it ...

After checking the checkbox to add a class, I then need to remove that class without having to interact with the entire document

When I click on a checkbox, an animation is added to a div. However, I am struggling to remove this animation unless I click elsewhere on the document. The goal is for the checkbox to both add and remove the class. JS $('#inOrder').click(functi ...

React Button Axios: A Primer for Complete Beginners

For the past few weeks, I've been using create-react-app and trying to modify the App.js file to include a button that executes an axios HTTP request when clicked. However, during my attempts, I keep running into errors like "unexpected token" in hand ...