In the last post we showed how to create a Blazor Web App. Today we will look into creating a custom 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:
It is placed, under the Razor 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>
Using the new Component
<main>
...skipping the top part
<Component></Component>
<article class="content px-4">
@Body
</article>
</main>
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>
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'
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>
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>
To fix this, we added this line into the Program.cs file
using Microsoft.AspNetCore.Components.WebAssembly;
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
MyWebAssembly Artifacts
MyWebAssembly 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)