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

Encountering an issue while trying to deploy my Next JS project on my local machine

I downloaded a fresh NextJS project from GitHub with just the basic setup and then ran the following commands: npm i npm run dev Whenever I try to access localhost:3000, I encounter this issue repeatedly: https://i.stack.imgur.com/QG9pd.png It appears to ...

When attempting to pass data to another page by clicking on a row, the result is that the data appears to be empty

I have been using the MUI-Datatable component, which is able to navigate to the next page. However, when I try to view the data on the History page, nothing appears. How can I resolve this issue? Data transfer to another page: Even though I can see the d ...

The Material UI library is signaling that there is an unidentified property called `selectable` being used with the <table> tag

Whenever I try to add the selectable attribute to the Table component in Material-UI using React JS, I encounter an error. Despite checking that selectable is indeed included in TableProps, the issue persists. List of Dependencies : "material-ui": "1.0.0 ...

Execute the component function located within one page using another page

Can someone help me understand how to trigger OnSwipe from inside a different JS file named CardFooter.js? This file contains a button with an OnClick event that triggers OnSwipe from the preceding JS file called CardItem.js. Both of these files are includ ...

Issue with mix-blend-mode causing text to not show up on top of the gradient

I am struggling to find a way to make text easily readable over my gradient background. Despite trying to use MUI's Typography or a simple <p>, the contrast isn't great as the text appears in black. After some research, I discovered that I ...

Whenever I include an onClick event to a div element, the entire webpage fails to display

Currently taking on the task of developing a seat booking website. I am encountering an issue with adding an event listener to a particular div element, which should trigger a function to store the value of the div. However, upon implementing the onClick e ...

Utilizing REACT to dynamically load multiple HTML elements

Recently, I began developing with React and wanted to load multiple new Input Fields and Labels in a Form using Hooks. However, when clicking the button, only one input field is created using the last value of my array. Upon checking the console, I notic ...

Locate specific phrases within the text and conceal the corresponding lines

I have a JavaScript function that loops through each line. I want it to search for specific text on each line and hide the entire line if it contains that text. For example: <input id="search" type="button" value="Run" /> <textarea id ...

Can someone explain why formik forms do not function within material-ui components?

Utilizing Axios to fetch data from an API for the input value, even with the enableReinitialize set to true, poses two challenges: The input does not update as intended The validation using Yup fails to work How can these issues be resolved? const va ...

Tips for effectively utilizing the display: inline property in conjunction with ng-repeat

I am struggling to create a timeline with a broken structure on my website. I suspect that the issue lies in using display:inline. When attempting to apply this to my site: https://i.stack.imgur.com/4Ur7k.png the layout gets distorted: https://i.stack.i ...

The efficiency of React Context API's setters is remarkably sluggish

I have a goal to implement a functionality where the background gradient of a page changes depending on whether the child's sublinks are expanded or collapsed. To achieve this, I am using the useContext hook. However, I've noticed that although e ...

Are all React libraries compatible with Node.js when requiring them?

Imagine a scenario where I can easily import a library in React by using the following code: import {Something} from someLibrary But the question arises, can I also utilize this same library in my Node.js backend like so? const someLibrary = require(someL ...

NPM performance lagging on Windows 10

My react application, created using Create-React-App, seems to be taking an unusually long time to start the development server and run build commands. When I use npm start, it runs react-scripts start, but takes nearly 10 minutes to start up. Even somethi ...

In search of a resolution for the error message "multipart: NextPart: bufio: buffer full" while attempting to upload an image via a fetch post request. Can anyone provide guidance

What steps can be taken to resolve the issue "multipart: NextPart: bufio: buffer full" when using a fetch post request to upload an image? I have a feature on my website that allows users to upload profile pictures. I use a fetch post request for this pur ...

How do I adjust the ul size to be proportionate to the header?

I have a list with corresponding hyperlinks in my code, and I am trying to make these elements the same size as the header. I attempted adding auto padding and height auto but it did not produce the desired result. Here is the HTML snippet: <header id ...

Close the Material UI ClickAwayListener when clicking on the component itself

I encountered an issue with a display sidebar Switch that appears within a Popper element. The desired behavior is for the Popper to disappear when clicked outside of its boundaries, but remain visible if clicked inside. However, clicking on the Switch or ...

Achieving bottom alignment for an element within a flex item: steps for success

I am dealing with a flex container that contains three flex items, each of which has a link that needs to be aligned at the bottom (all links should be bottom middle-aligned). The flex-items are stretched and do not have a fixed height, similar to the fle ...

Looking to create circular text using HTML, CSS, or JavaScript?

Is there a way to generate curved text in HTML5, CSS3, or JavaScript similar to the image linked above? I've experimented with transform: rotate(45deg); but that just rotates the text without curving it. Additionally, when using Lettering.JS to curve ...

Issues with Google Chrome truncating the end of lengthy pages

While working on a website project, I encountered an issue with Chrome where loading a lengthy page results in a strange box covering the bottom portion of the content. Interestingly, the same pages appear fine on Safari and Firefox, indicating that the pr ...

What advantages can be gained from having multiple package.json files within a single application?

Embarking on the journey of creating my inaugural full react web application entirely from scratch. Previously, I've mainly worked on assignments that were partially pre-made for me. While setting up my project, I couldn't help but notice that I ...