Search code examples
blazormudblazor

Truncate text in a MudTable cell


How can I instruct a MudTable to truncate text in a cell instead of allowing the text to wrap onto the next line?

Here is a code sample

<MudTable Items="@data">
    <ColGroup>
        <col style="width: 80%" />
        <col style="width: 20%" />
    </ColGroup>
    <HeaderContent>
        <MudTh>Name</MudTh>
        <MudTh>Description</MudTh>
    </HeaderContent>
    <RowTemplate>
        <MudTd>@context.Name</MudTd>
        <MudTd>@context.Description</MudTd>
    </RowTemplate>
</MudTable>

@code {
    public string Text { get; set; } = "????";
    public string ButtonText { get; set; } = "Click Me";
    public int ButtonClicked { get; set; }

    public class TableStructure
    {
        public string Name { get; set; } = string.Empty;
        public string Description { get; set; } = string.Empty;
    }

    private List<TableStructure> data = new();

    protected override void OnInitialized()
    {
        data.Add(new() { Name = "Name1", Description = "Description 1"});
        data.Add(new() { Name = "Name2", Description = "Description 2"});
        data.Add(new() { Name = "Name3", Description = "Description 3"});
        data.Add(new() { Name = "Name4", Description = "Description 4 - This is a really long description that is the problem"});
    }

}

How do I convert the description for the final item from the wrapped text to something like " Description 4 - this is......."

I've found css that allows word breaks but nothing that supports truncating.

Any ideas? Is there something I can add at a project level that each table can inherit?

Here is a playground https://try.mudblazor.com/snippet/mkmSaevAnmAsvCEE


Solution

  • You can style the <MudTd> element to achieve this.

    <MudTable Items="@data">
        <ColGroup>
            <col style="width: 80%" />
            <col style="width: 20%" />
        </ColGroup>
        <HeaderContent>
            <MudTh>Name</MudTh>
            <MudTh>Description</MudTh>
        </HeaderContent>
        <RowTemplate>
            <MudTd>@context.Name</MudTd>
            <MudTd Style="max-width: 1px;overflow-wrap: break-word;white-space: nowrap;overflow: hidden;">@context.Description</MudTd>
        </RowTemplate>
    </MudTable>
    

    These are the css styles you need to completely ignore the text if it overflows.

    Note: max-width needs to be >= 0.

    {
        max-width: 1px;
        overflow-wrap: break-word;
        white-space: nowrap;
        overflow: hidden;
    }
    

    Or, if you want the cell to be scrollable instead then:-

    overflow-y: hidden;
    // or 
    overflow: auto;
    

    Demo 👉MudBlazor Snippet