Hello!

Let’s see how you can transfer data from one component to another.

Button

I will create a component called ThumbButton which will contain two buttons. Depending on which button is pressed, the corresponding method will be called and the data will be transferred to the parrent component. @Onclick specifies which method will be executed when the button is pressed.

To pass data to the parrent component, a property of type EventCallback<Thumb> is used, where Thumb is enum. Instead of enum there can be any other type of data. In the method ThumbUp and ThumbDown I call OnVote.InvokeAsync in which the corresponding enum is passed. This call passes data to the parrent component.

<button class="btn btn-primary mx-2" @onclick="ThumbUp">
    <span class="oi oi-thumb-up"></span>
</button>

<button class="btn btn-danger mx-2" @onclick="ThumbDown">
    <span class="oi oi-thumb-down"></span>
</button>

@code {

    public EventCallback<Thumb> OnVote { get; set; }

    private void ThumbUp()
    {
        OnVote.InvokeAsync(Thumb.Up);
    }

    private void ThumbDown()
    {
        OnVote.InvokeAsync(Thumb.Down);
    }

    public enum Thumb
    {
        Up,
        Down
    }
}

You can now reuse this component on any page.

Button Component on page

Now take the page Counter. And add the newly created component with a button. Let’s start with the code. I will create two properties isThumbUp and isThumbDown of type bool. Depending on which property is set to true, the corresponding data will be displayed. Also, if one of these properties becomes true, the button will disappear.

To get data from a button component, you need a handler that will change the values ​​of isThumbUp and isThumbDown in response to the button press. It added in the same way as any other component. But method handler need to be added to retreive data <ThumbButton OnVote ="OnVotedHandler"></ThumbButton>. The handler method must accept a parameter of the type received from the button. private void OnVotedHandler(ThumbButton.Thumb result). Depending on what value came to the input, the values ​​of the parameters isThumbUp and isThumbDown are set.

@page "/counter"

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@if (isThumbUp)
{
    <p class="text-success">Your thumb is up</p>
}

@if (isThumbDown)
{
    <p class="text-danger">Your thumb is down</p>
}

@if (!isThumbDown && !isThumbUp)
{
    <div class="row">
        <div class="col-12">
            <ThumbButton OnVote="OnVotedHandler"></ThumbButton>
        </div>
    </div>
}

@code
{
    private bool isThumbUp = false;
    private bool isThumbDown = false;
    private void OnVotedHandler(ThumbButton.Thumb result)
    {
        if (result == ThumbButton.Thumb.Up)
        {
            isThumbUp = true;
        }
        else if (result == ThumbButton.Thumb.Down)
        {
            isThumbDown = true;
        }
    }
}

EventDemo