How to create a Banner in Blazor

 




I found another small control I wanted to include in my UI component library.  It is a banner control that you can place on the top of a page.  The banner can be used to alert the user to take action, to let the user know about a system issue, or even to use ads.

On the initial page load, we display the banner with its messaging.  We provide a close button to allow the user to dismiss, as shown in the image above.


HTML and CSS

The HTML is just a couple of divs and some text.  

      <div class="banner">
        <div class="banner__content">
          <div class="banner__text">
            <strong>Reminder:</strong> Coding with David is fun and exciting
          </div>
          <button class="banner__close" type="button">
            <span class="material-icons">
              close
            </span>
          </button>
        </div>
      </div>

The CSS is standard to style the container, the text, and the button.

Close Event

We are getting pretty good at handling a button click in Blazor.  On this click, we change the style of the top container to:

    display: none;

This will remove the banner from the view.

    public void CloseBanner()
    {
        bannerStyle = "banner_close_display";
    }
    

Make it a Component

Of course, we wanted to make this into a component of our library.  We just needed to add a parameter for the message:

    [Parameter]

    public string Message { get; set; }

Then when we call it:

    <BannerComponent 
        Message="<strong>Reminder:</strong> Coding with David is fun and       exciting">
    </BannerComponent>

This code does have an issue.  The "<strong> " HTML tag shows as actual text, which is not what we want.

We want to have the HTML applied to the message.

Banner Message

To accomplish the task of applying the HTML within the message to the page, we will need to convert the Message string to a MarkupString.  We will do this within the OnInitializedAsync method.

    private MarkupString bannerbody = new MarkupString();

    protected override async Task OnInitializedAsync()
    {
        if (!string.IsNullOrEmpty(Message))
        {
            bannerbody = (MarkupString)Message;
        }
        else
        {
            bannerStyle = "banner_close_display";
        }
        await Task.CompletedTask;
    }

If the message is blank, we will just not show it.

Summary

This turned out to be a quick and easy component that we can reuse when needed.   The use of the MarkupStirng was a cool trick to handle HTML tags within the message as well.  These simple components may seem like they are not that hard to implement but it seems like I also run into a use case of the control that I was not aware of.


[Piggy back on dcode]


[source]

Comments

Popular posts from this blog

Yes, Blazor Server can scale!

Blazor new and improved Search Box

Blazor Wizard Step Component