Creating Advanced Blazor Components (Part 2)

 






Building an Alert Component

To gain a clearer insight into using render fragments, we’ll create an alert component. The components provided by default utilize Bootstrap, so we will adopt that approach for our component as well. Bootstrap offers numerous components that can be easily adapted for Blazor. In large projects with multiple developers, creating components helps ensure that the entire team maintains a consistent coding style.

Let's build a simple alert component, based on Bootstrap:

  • Create a folder by right-clicking on MyBlogServerSide project | Add | New folder and name the folder Components.

  • Create a new Razor file by right-clicking on Components | Add | Razor component and name the component Alert.razor.

  • Replace the content with the Alert.razor file.

  • Add a code section with a RenderFragment property called ChildContent and replace the alert text with the new property.

  • In the code section, add enum containing the different styles available.

  • Add a parameter/property for the enum style.

  • The final step is to update the class attribute for div. Change the class attribute on the first line of the complete file.

  • Right-click on the Pages folder, select Add | Razor component, and name it AlertTest.razor. The page will show three alert components- The first one has the Danger style, and by default, it is going to use the property called ChildContent. For the second one, if you are using more render fragments in your component, you will have to set them with full names. The last one will give the property the default render fragment specified in the component.

  • Run the project and navigate to /AlertTest to see the test page.

We have finished our first reusable component!

Conclusion

The first reusable alert component is created.

 
































































Comments

Popular posts from this blog

How AMI Store & Restore Works?

Create A Store Image Task

Information Protection Scanner: Resolve Issues with Information Protection Scanner Deployment