How do you render a list of components in a loop (Blazor)?

Viewed 4096

I must be missing something very obvious with blazor... I want to simply render a list containing a component, yet there's no (obvious?) way to reference the iterator (which is a component) for rendering?

TodoList.razor

<input @bind="_newTodo" />
<button @onclick="@AddTodoItem">+</button>

@foreach (TodoItem todoItem in _todoItems)
{
    // todoItem is a razor component, yet I can't simply render it here?
    // <todoItem />
}

@code {
    private IList<TodoItem> _todoItems = new List<TodoItem>();
    private string _newTodo;

    private void AddTodoItem()
    {
        if (!string.IsNullOrWhiteSpace(_newTodo))
        {
            _todoItems.Add(new TodoItem { Title = _newTodo });
            _newTodo = string.Empty;
        }
    }
}

TodoItem.razor

<span>@Title</span>

@code {
    public string Title { get; set; }
}
2 Answers

In React that is something very simple to do and would work the same way you just did, but in Blazor I don't think you can do that in the way you are trying.

One solution to do that is have a class that holds the component properties and pass the properties to it

<input @bind="_newTodo" />
<button @onclick="@AddTodoItem">+</button>

@foreach (TodoItem todoItem in _todoItemsDto)
{
    // Pass the Dto properties to the component
    <TodoItem Title="@todoItem.Title" />
}

@code {
    private IList<TodoItemDto> _todoItemsDto = new List<TodoItemDto>();
    private string _newTodo;

    class TodoItemDto {
        public string Title { get; set; }
    }

    private void AddTodoItem()
    {
        if (!string.IsNullOrWhiteSpace(_newTodo))
        {
            _todoItems.Add(new TodoItemDto { Title = _newTodo });
            _newTodo = string.Empty;
        }
    }
}

I just built a Help system that has a LinkButton component, and I render it like this:

 foreach (HelpCategory category in Categories)
 {
     <LinkButton Category=category Parent=this></LinkButton>
     <br />
 }

Each HelpCategory has one or more Help Articles that can be expanded.

Here is the code for my LinkButton, it does more of the same:

@using DataJuggler.UltimateHelper.Core
@using ObjectLibrary.BusinessObjects

@if (HasCategory)
{
    <button class="linkbutton" 
    @onclick="SelectCategory">@Category.Name</button>

    @if (Selected)
    {
        <div class="categorydetail">
            @Category.Description
        </div>
        <br />
        <div class="margintop">
            @if (ListHelper.HasOneOrMoreItems(Category.HelpArticles))
            {
                foreach (HelpArticle article in Category.HelpArticles)
                {
                    <ArticleViewer HelpArticle=article Parent=this> 
                    </ArticleViewer>
                    <br />
                    <div class="smallline"></div>
                }
            }
        </div>
    }
}
Related