Skip to content
On this page

Nesting Components

Note

This guide assumes you have read the component documentation, the pages documentation and understand the way Leaf UI components/pages work.

Components can be created and used as both pages and components. This means that you can nest components inside of other components. The idea of nesting components is to create a component that can be used in multiple places, and can be reused in different ways.

Creating a nested component

To create a nested component, you need to create the component you want to nest. In this example, we will create a Card component that will be used to display a title and some content.

<?php

use Leaf\UI;
use Leaf\UI\Component;

class Card extends Component
{
  public $key = 'Card';

  public function render()
  {
      return UI::view('card.html');
  }
}
<div class="card">
    <h2 class="card-title">{{ $title }}</h2>
    <div class="card-content">{{ $content }}</div>
</div>

Now that we have created the component, we can use it in a page or another component using the @component directive.

@component('Card', [
  'title' => 'My Card',
  'content' => 'This is my card'
])

Note how we pass the title and content to the component using the second argument of the @component directive. This is how we pass data to the component. You can take those as props in React and Vue.

Example Usage:

<h2>Cards</h2>
<div class="cards">
  @component('Card', [
    'key' => 'Card1',
    'title' => 'My Card',
    'content' => 'This is my card'
  ])
  @component('Card', [
    'key' => 'Card2',
    'title' => 'My Card',
    'content' => 'This is my card'
  ])
  @component('Card', [
    'key' => 'Card3',
    'title' => 'My Card',
    'content' => 'This is my card'
  ])
</div>
Nesting Components has loaded