How to create a component dynamically through its assembly type path and reflection? #26111
-
Hi: |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 3 replies
-
You shouldn't instantiate the component yourself. You need the renderer to instantiate it for you, because then it becomes part of the component hierarchy, gets wired into all the re-rendering logic, and has its lifecycle managed by the framework. One way to do this is create a class called public static class RenderingHelpers
{
public static readonly Func<Type, IDictionary<string, object>, RenderFragment> RenderComponent = (componentType, parameters) => builder =>
{
builder.OpenComponent(0, componentType);
if (parameters != null)
{
foreach (var kvp in parameters)
{
builder.AddAttribute(1, kvp.Key, kvp.Value);
}
}
builder.CloseComponent();
};
} Then inside any of your
... to render a component by type name and optionally pass a dictionary of parameters. |
Beta Was this translation helpful? Give feedback.
-
Hi @SteveSandersonMS :
|
Beta Was this translation helpful? Give feedback.
-
I would generally recommend trying to minimize the amount of manual rendertreebuilder logic you write. It's easy to make small mistakes that would result in suboptimal diffing performance, or even illegal trees and undefined behavior. For example there is a mistake in the logic you've posted above (passing The |
Beta Was this translation helpful? Give feedback.
-
Hi @SteveSandersonMS: |
Beta Was this translation helpful? Give feedback.
You shouldn't instantiate the component yourself. You need the renderer to instantiate it for you, because then it becomes part of the component hierarchy, gets wired into all the re-rendering logic, and has its lifecycle managed by the framework.
One way to do this is create a class called
RenderingHelpers
containing: