Reputation: 743
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?
Upvotes: 1
Views: 2867
Reputation: 743
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
Upvotes: 1
Reputation: 30177
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.
Upvotes: 0