Components are reusable UI pieces (like buttons, forms, or entire pages).
Defined in
.razor
files (e.g.,MyComponent.razor
).Combine HTML + C# logic using Razor syntax.
Razor Syntax Basics
Create a Simple Component
Let’s create a component that toggles text visibility.
Data Binding
Event Handling
Respond to user actions (clicks, input changes, etc.).
Event | Example |
Button Click | @onclick="MethodName" |
Input Change | @oninput="MethodName" |
Form Submission | OnValidSubmit="HandleSubmit" |
Practice Task
Create a "Like Button" Component:
Show a button with a thumbs-up icon (👍).
Display the number of likes.
When clicked, increment the likes count.
Common Issues (For Beginners)
Missing
@code
Block: Ensure logic is inside@code { ... }
.Incorrect Event Names: Use
@onclick
, notonclick
.Case Sensitivity:
@bind
is lowercase, not@Bind
.
Key Takeaways
Components are reusable and can have their own logic.
Razor Syntax lets you mix HTML and C# with
@
.Data Binding keeps UI and variables in sync.
Events like
@onclick
let you handle user interactions.