Search code examples
c#blazorblazor-webassembly

Blazor : Optional parameters for the razor component


I am working on a blazor application which has a MainLayout where we are rendering DynamicComponent based on a list of types which are specified by the page. Also in the parameter for the second component there is a eventcallback that will notify any value changes in the component

MainLayout.razor

@foreach (var item in BaseParameters)
{
    <DynamicComponent Type="@item" Parameters="parameters" />
}

@code
{
public List<Type> BaseParameters { get; set; } = new List<Type>(typeof(MyComponent1),typeof(MyComponent2),...);

Dictionary<string, object>? parameters = new() { { "OnInputCallBack", EventCallback.Factory.Create<EventCallbackArgs>(this, GetChangedValue) } };
}

Now some of my components do not want to implement "Parameters" parameter and my list of types "BaseParameters" have mix of components (some has "Parameters" and some dont).

As of now I am getting null error while rendering, is there any way that I can avoid this?


Solution

  • To handle a mix of components, some of which do not implement the "Parameters" parameter, you can use reflection to check if the component has a specific parameter before attempting to pass it. This way, you can avoid the null reference error when rendering components that do not expect the "Parameters" parameter.

    Here is an updated version of your MainLayout.razor that performs this check:

    @foreach (var item in BaseParameters)
    {
        if (HasParametersProperty(item))
        {
            <DynamicComponent Type="@item" Parameters="parameters" />
        }
        else
        {
            <DynamicComponent Type="@item" />
        }
    }
    
    @code
    {
        public List<Type> BaseParameters { get; set; } = new List<Type> { typeof(MyComponent1), typeof(MyComponent2), /* other component types */ };
    
        Dictionary<string, object>? parameters = new() { { "OnInputCallBack", EventCallback.Factory.Create<EventCallbackArgs>(this, GetChangedValue) } };
    
        private bool HasParametersProperty(Type componentType)
        {
            return componentType.GetProperty("Parameters") != null;
        }
    }
    

    This way, only the components that expect the Parameters parameter will receive it, and you can avoid the null reference error for those components that do not implement the Parameters parameter.