Conditional Blazor Styles (without the if statements)
If you’re building Blazor components you’re probably used to driving the UI from data.
At its simplest this might be to show a value in the UI using one-way binding:
But what if you want to alter the appearance of the component, beyond just showing data, say to change the colour of a border, or background, in response to a value found in the data?
For that we need a little conditional logic, and the ability to provide different CSS classes for different scenarios.
Here’s a simple example.
Let’s say we have a list of Panels, and some of those panels are flagged up as ‘important’
Dashboard.razor
Render different UI depending on the flag#
From here we can update our markup to read that flag and render something different…
There are a few ways to handle this.
We could put some sort of conditional code in the markup itself, using if
statements.
In practice this would likely lead to some duplicated markup as we attempt to render different div
elements based on the Important
flag.
We could render an entirely different panel component (we could create an ImportantPanel
and a ‘regular’ Panel
).
I might consider this if Important
panels had a bit more specific UI and/or logic.
But in this case, for the sake of a slightly different looking border, an entirely separate component seems like overkill.
My preferred “simplest first step” approach here is to create a method in @code
which returns a string with any additional CSS classes we want our card
component to use.
Now if we invoke this cardClass
method, and give it an instance of Panel
it will use the Panel’s Important
flag to decide whether to return the border-danger CSS class or not.
NOTE
What’s with the =>
That syntax may look a little odd if it’s the first time you’re seeing it.
This is something known as an expression bodied lambda.
It’s an alternative way to declare a method.
We could equally have written the method out “long form” like this:
Finally, we can call this cardClass
method in our markup.
Now we can have angry looking red-bordered panels, simply by setting our panel’s Important
flag to true.
Are you getting the most out of Blazor?
Make more of Blazor's component model, and build modern, reliable web applications, faster with .NET.
Speed up your development