Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Rendering a Component Instance With Razor Components in a Blazor App

DZone's Guide to

Rendering a Component Instance With Razor Components in a Blazor App

We take a quick dive in the Razor view engine and how developers can use it to render component instances on their web pages.

· Web Dev Zone ·
Free Resource

Building real-time chat? Enroll in a Free Course on Mobile Chat Development. 

In some child and parent component situations it would be good if you could render, or at least get access to, an instance of a Razor Component.

Given the following scenario where we try to render an instance of the Counter component inside the Index component:

<h1>Hello, world!</h1>

Welcome to your new app.

@counterInstance

@functions{
    Counter counterInstance = new Counter();
}

The following doesn't work as it only draws the type name of the component:

There are a couple options around this.

Capturing a Reference

In many (if not most?) cases you should let Razor Components take care of creating the instance of your component and then use the "ref" keyword to capture the rendered instance:

<h1>Hello, world!</h1>

Welcome to your new app.

@DrawCounter()

@functions{

    private Counter _myCounter = null;

    RenderFragment DrawCounter()
    {
        return new RenderFragment(builder =>
        {
            builder.OpenComponent<Counter>(0);
            builder.AddComponentReferenceCapture(1, inst => { _myCounter = (Counter)inst; });
            builder.CloseComponent();
        });
    }

Reflection

If you really want, you can access the RenderFragment of the instance using reflection and then draw that:

Welcome to your new app.

@RenderContent(counterInstance)

@functions{
    Counter counterInstance = new Counter();

    RenderFragment RenderContent(ComponentBase instance)
    {
        var fragmentField = GetPrivateField(instance.GetType(), "_renderFragment");

        var value = (RenderFragment)fragmentField.GetValue(instance);

        return value;
    }

    //https://stackoverflow.com/a/48551735/66988
    private static FieldInfo GetPrivateField(Type t, String name)
    {
        const BindingFlags bf = BindingFlags.Instance |
                                BindingFlags.NonPublic |
                                BindingFlags.DeclaredOnly;

        FieldInfo fi;
        while ((fi = t.GetField(name, bf)) == null && (t = t.BaseType) != null) ;

        return fi;
    }

Power realtime chat, IoT and messaging apps at scale. Pubsub realtime messaging, functions, chat, presence, push, notifications, blocks catalog and more.

Topics:
web dev ,razor components ,blazor tutorial ,view engines

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}