Day 2: Blazor Components & Razor Syntax

What is a Component?

  • 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.).

EventExample
Button Click@onclick="MethodName"
Input Change@oninput="MethodName"
Form SubmissionOnValidSubmit="HandleSubmit"

Practice Task

Create a "Like Button" Component:

  1. Show a button with a thumbs-up icon (👍).

  2. Display the number of likes.

  3. When clicked, increment the likes count.

Common Issues (For Beginners)

  • Missing @code Block: Ensure logic is inside @code { ... }.

  • Incorrect Event Names: Use @onclick, not onclick.

  • 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.