DEV Community

Cover image for Blazor Custom Components
John Peters
John Peters

Posted on

Blazor Custom Components

In the last post we showed how to create a Blazor Web App. Today we will look into creating a custom component.
Add a Razor Component

Right click on the Shared folder, select Add/Razor Component. Take the default name of Component.razor for now. Here's a trick, add a CSS style sheet using the same naming convention. Component.Razor.css and look what happens:
adding a stylesheet

It is placed, under the Razor component definition.

Under the component definition

A great example of convention over configuration.

We want to do this so we can influence the style of just our component. This is the markup we put in. It's a DateTime component now.



<div>
@DateTime.Now.ToShortDateString()
</div> 


Enter fullscreen mode Exit fullscreen mode

Using the new Component



    <main>
       ...skipping the top part
        <Component></Component>
        <article class="content px-4">
            @Body
        </article>
    </main>


Enter fullscreen mode Exit fullscreen mode

Showing the datetime component

Renaming a Component

We are easily able to rename the file, but the prior Component tag does not follow the rename.

This forces us to manually make the change. Like this:



 <main>
       ...Top part left out
       <DateTime></DateTime>
        <article class="content px-4">
            @Body
        </article>
 </main>


Enter fullscreen mode Exit fullscreen mode

Too bad the refactor also didn't correct the prior HTML markup, but Visual Studio does have a Replace in Files utility that will.

Rebuilding The Solution

CS0117 'DateTime' does not contain a definition for 'Now'
DateTime does not contain a definition for Now

That is odd, because until recompiled, there was no error and it showed in the local instance of the page when refreshed.

The simple fix is to include the namespace:



<div>@System.DateTime.Now.ToShortDateString()</div>


Enter fullscreen mode Exit fullscreen mode

TS6053: Blazor.webassembly.js not found error.
This error was caused by the index.html file, on this line:



 <script src="_framework/blazor.webassembly.js"></script>


Enter fullscreen mode Exit fullscreen mode

To fix this, we added this line into the Program.cs file



using Microsoft.AspNetCore.Components.WebAssembly;


Enter fullscreen mode Exit fullscreen mode

One last thing, we had to rename our DateTime component to MyDateTime because it conflicted with Syste.DateTime.

Once we did that everything compiled at the solution layer.

The Solution's Debug Compile Output

Debug Compile Output

MyWebAssembly Artifacts

MyWebAssembly Artifacts

MyWebAssembly Object Browser

Object Browser

All very cool but "How do we reuse these components in other solutions?"

We'll figure that out in next article.

Top comments (0)