Exercise - Add a component
In this exercise, you add a Razor component to the home page of your app.
Add the Counter component to the Home page
Open the Components/Pages/Home.razor file.
Add a
Countercomponent to the page by adding a<Counter />element at the end of theHome.razorfile.@page "/" <PageTitle>Home</PageTitle> <h1>Hello, world!</h1> Welcome to your new app. <Counter />Apply the change by restarting the app or using hot reload. The
Countercomponent shows up on the home page.
Modify a component
Define a parameter on the Counter component to specify how much it increments with every button click.
Add a public property for
IncrementAmountwith a[Parameter]attribute.Change the
IncrementCountmethod to use theIncrementAmountvalue when incrementing the value ofcurrentCount.The updated code in Counter.razor should look like this:
@page "/counter" @rendermode InteractiveServer <PageTitle>Counter</PageTitle> <h1>Counter</h1> <p role="status">Current count: @currentCount</p> <button class="btn btn-primary" @onclick="IncrementCount">Click me</button> @code { private int currentCount = 0; [Parameter] public int IncrementAmount { get; set; } = 1; private void IncrementCount() { currentCount += IncrementAmount; } }In
Home.razor, update the<Counter />element to add anIncrementAmountattribute that changes the increment amount to 10, as shown by the last line in the following code:@page "/" <h1>Hello, world!</h1> Welcome to your new app. <Counter IncrementAmount="10" />Apply the changes to the running app.
The
Homecomponent now has its own counter that increments by 10 each time the Click me button is selected, as shown in the following image.
The
Countercomponent at/countercontinues to increment by one.