Search code examples
blazorblazor-client-side

Blazor - Porting a Admin Template


I have a HTML Admin template that I'm need to port Blazor.

All CSS are working fine, the only problem I have right now is that the Admin template uses jQuery to do a lot of CSS manipulation and pretty style things.

At first I didn't want to use jQuery because when you think using Blazor is like trying to get away from Javascript, but because in this Admin template there are some nice left menu animations and control of hover CSS styles and many other things I guess the easies way would be to add jQuery.

The template uses an app.js file where it starts with:

  $(window).on('load', function () {
  .....
  }

Insde the load event many things are setup.

I read that in order to user jQuery with Blazor you need to let Blazor control the DOM, so I wont have in my jquery app.js file a onReady or Load event. I will need to call from Blazor an Initializer method that will act as the Load event.

My questions are:

  1. What is the life cycle method that I have to use in Blazor to run this? Because Blazor is an SPA this initial setup of components will be called just once or when the page is refreshed, should I use OnInitialized or OnAfterRenderAsync(bool firstRender).

  2. The Blazor life cycle method that will run this initial setup has to run on the main routing path @page "/"?

  3. Using jQuery in Blazor is against its conceptual design or there is no problem or bad pattern to use it? Im not going to use any ajax stuff, etc is just basically DOM manipulation that is pretty easy to do with jQuery.


Solution

  • You should use the OnAfterRenderAsync(bool firstRender) method to initialize your JavaScript objects, and only once; that is, your code should be wrapped within the if statement like this:

    if( firstRender )
    {
    // Initialization code comes here...
    }
    

    The Blazor life cycle method that will run this initial setup has to run on the main routing path @page "/"?

    Not necessarily... It should run on the routing path of the component page where you're going to use it.

    Using jQuery in Blazor is against its conceptual design or there is no problem or bad pattern to use it?

    The process of finding best practices in Blazor is ongoing. Personally, I'm against using jQuery in Blazor, and I'd convert a jQuery widget to a Blazor component, using JSInterop. But this is only me. Others, think otherwise, or at least do otherwise.

    In your case, however, the best thing to do is to check if the given jQuery code works seamlessly with the Blazor rendering system. Perhaps if it's only "menu animations and control of hover CSS styles", no issues are really expected to arouse. But you can never know. So as I've said above, you should do it, and test if it works with no issue.