1

I have 2 components, one that I wish to display if the browser is Mobile, the other if it is tablet/desktop.

@if(isMobile)
{
   <MobileComponent />
}
else
{
   <DesktopComponent />
}

I am looking to not have the Mobile Component in the DOM at all when on desktop and vice versa so i dont want to do a CSS visibility. Id rather only the one be rendered. What is the best approach to determine if the browser is a Mobile browser so I can set isMobile accordingly?

JoeyD
  • 693
  • 4
  • 25

2 Answers2

1

Here is the method that I created. Add js to your Index.html page with the following function

<script>

    function isDevice() {
        return /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile/i.test(navigator.userAgent);
    }

</script>

Then on any component where you want to know if the browser is mobile add the following

protected override async Task OnInitializedAsync()
{
    IsMobile = await JSRuntime.InvokeAsync<bool>("isDevice");
}

If you are using Chrome to debug, when you set the browser to mobile the value will be true

JoeyD
  • 693
  • 4
  • 25
0

If you have the above code in the Razor markup for the page/component, <MobileComponent /> will only be rendered and therefore appear in the Dom when ismobile is true. And visa versa of course.

In Blazor you don't need to screw around with css visibility, code it like you have. A huge amount of javascript css manipulation code just ain't needed anymore.

MrC aka Shaun Curtis
  • 19,075
  • 3
  • 13
  • 31
  • 1
    Im aware of that. The question was more in regards to how to determine isMobile. What is the best way of acquiring if the browser is a mobile browser so i can set isMobile correctly – JoeyD Feb 09 '21 at 01:41
  • OK, that wasn't clear. try [here](https://stackoverflow.com/questions/62270247/how-do-i-detect-mobile-devices-in-blazor-server-side-application) – MrC aka Shaun Curtis Feb 09 '21 at 14:18