Fragment
The <Fragment> component allows you to return multiple sibling elements from a PHPX component using HTML heredocs without wrapping them in a single DOM node. It supports the shorthand syntax <>...</>.
Use Cases
- Return multiple sibling elements without an unnecessary parent
div. - Preserve semantic HTML structure in layouts (e.g., lists or tables).
- Optionally wrap children dynamically using the
asprop.
Component Example
<?php
declare(strict_types=1);
namespace Lib\PHPX\Components;
use Lib\PHPX\PHPX;
use Lib\PHPX\Fragment;
class ClassName extends PHPX
{
public function __construct(array $props = [])
{
parent::__construct($props);
}
public function render(): string
{
return <<<HTML
<>
<h1 class="text-2xl font-bold">Heading</h1>
<p class="text-muted-foreground">
This is a paragraph inside a fragment.
</p>
</>
HTML;
}
}
Note
This usage is required when using
<<<HTML return blocks, as PHPX requires a single root node for parsing. The <> acts as that invisible wrapper.
Props
| Prop | Type | Description |
|---|---|---|
| as | string | Optional. Renders a specific tag instead of a fragment (e.g. div, section). |
| class | string | Optional. Tailwind CSS class names, applied only when the as prop is used. |
Behavior
- If no
asis defined, the fragment renders children directly without a wrapper. - If
asis provided, a wrapper element renders with the merged attributes.
Wrapped Example (with "as")
public function render(): string
{
return <<<HTML
<Fragment as="section" class="bg-secondary p-4 rounded-md">
<h2 class="font-bold">Wrapped Title</h2>
<p class="text-sm text-muted-foreground">
This is wrapped in a section tag.
</p>
</Fragment>
HTML;
}
Pro Tip
Always use <></> inside render() when returning multiple root elements. It keeps your DOM clean and your HTML structure valid.