Fragment

The <Fragment> component allows you to return multiple sibling elements from a PHPX component using <<<HTML without wrapping them in a single tag. It behaves like React.Fragment, and supports a shorthand syntax using <>...</>.

Use Cases

  • Return multiple sibling elements from a component without adding an unnecessary wrapper.
  • Preserve semantic HTML structure when a wrapper element is not needed.
  • Optionally wrap children with a custom tag (e.g., section, main, etc.) using the as prop.

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-gray-500">This is a paragraph inside a fragment.</p>
        </>
        HTML;
    }
}

Note: This usage is required when using <<<HTML return blocks in components, where only one root node is allowed. <> or <Fragment> acts as that invisible wrapper.

Props

  • as: Optional — render a specific tag instead of a fragment (e.g. div, section).
  • class: Optional — TailwindCSS class names, applied only when as is used.

Behavior

  • If no as is defined, the fragment will not render any HTML wrapper.
  • If as is provided, a wrapper element will be rendered with merged attributes and class.
  • Supports short syntax <></> for clean and readable components.

Wrapped Example (with "as")

public function render(): string
{
    return <<<HTML
    <Fragment as="section" class="bg-gray-100 p-4">
        <h2>Wrapped Title</h2>
        <p>This is wrapped in a section tag.</p>
    </Fragment>
    HTML;
}

Tip: If your component needs to return multiple elements in a <<<HTML block, always wrap them in <></> or <Fragment></Fragment>.