Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Mesh Laravel Package

ethanbarlo/mesh

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require ethanbarlo/mesh
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="EthanBarlo\Mesh\MeshServiceProvider"
    
  2. Basic Usage

    • Create a Livewire component (e.g., Counter.php):
      namespace App\Http\Livewire;
      
      use EthanBarlo\Mesh\MeshComponent;
      use Livewire\Component;
      
      class Counter extends Component
      {
          public $count = 0;
      
          public function increment()
          {
              $this->count++;
          }
      
          public function render()
          {
              return MeshComponent::render('Counter', [
                  'count' => $this->count,
                  'increment' => $this->increment,
              ]);
          }
      }
      
  3. React Component Create a React component in resources/js/components/Counter.jsx:

    import { useState } from 'react';
    
    export default function Counter({ count, increment }) {
        return (
            <div>
                <p>Count: {count}</p>
                <button onClick={increment}>Increment</button>
            </div>
        );
    }
    
  4. Mount the Component In your Blade view:

    @livewire('counter')
    

First Use Case

Replace a traditional Livewire component with a React frontend while retaining Livewire’s reactivity. For example, a form with validation:

  • Use Livewire for state management ($errors, $submitted).
  • Use React for dynamic UI (e.g., real-time validation feedback).

Implementation Patterns

Workflow: Hybrid Livewire + React

  1. State Management

    • Push Livewire state (e.g., $formData, $errors) to React via MeshComponent::render().
    • Example:
      return MeshComponent::render('UserForm', [
          'formData' => $this->formData,
          'errors'   => $this->errors,
          'submit'   => $this->submitForm,
      ]);
      
  2. Event Handling

    • Bind Livewire methods to React events (e.g., onClick={submit}).
    • Use wire:ignore on the Livewire component’s root element to prevent double-rendering:
      @livewire('user-form', key('user-form'))
      <div wire:ignore>
          {{ $slot }}
      </div>
      
  3. Dynamic Data Fetching

    • Fetch additional data in Livewire’s updated() or mount() and pass it to React:
      public function mount()
      {
          $this->extraData = Api::fetchData();
      }
      
      public function render()
      {
          return MeshComponent::render('Dashboard', [
              'extraData' => $this->extraData,
          ]);
      }
      
  4. Reactivity

    • Use Livewire’s updated() to trigger React re-renders when data changes:
      public function updatedCount()
      {
          $this->dispatch('count-updated', count: $this->count);
      }
      
    • Listen in React with window.addEventListener('count-updated', ...).

Integration Tips

  1. Vite/Laravel Mix Ensure your React components are compiled and available globally. Example vite.config.js:

    export default {
        build: {
            outDir: 'public/js',
            emptyOutDir: true,
        },
    };
    
  2. TypeScript Support Add type definitions for Mesh props in resources/js/types/mesh.d.ts:

    declare module '*.mesh' {
        import { ComponentType } from 'react';
        const MeshComponent: ComponentType<{ count: number; increment: () => void }>;
        export default MeshComponent;
    }
    
  3. Testing

    • Test Livewire logic with PHPUnit.
    • Test React components in isolation with Jest/React Testing Library.
    • Use Livewire’s test() helper to simulate user interactions:
      $this->call('increment')->assertHasNoErrors();
      
  4. Fallback for Non-JS Users Provide a server-side fallback in Blade:

    @livewire('counter')
    @if(!app()->isJson())
        <div wire:ignore>
            <p>Count: {{ $count }}</p>
            <button wire:click="increment">Increment</button>
        </div>
    @endif
    

Gotchas and Tips

Pitfalls

  1. Double Rendering

    • Issue: React and Livewire both render the same DOM, causing conflicts.
    • Fix: Use wire:ignore on the Livewire component’s root element and ensure React mounts inside it.
  2. State Synchronization

    • Issue: React and Livewire states drift if not synchronized.
    • Fix: Use Livewire’s updated() to push changes to React or vice versa via events.
  3. CSRF Token Mismatch

    • Issue: React’s form submissions may fail with CSRF errors.
    • Fix: Include the CSRF token in your React app’s global headers or use Livewire’s @csrf directive in Blade.
  4. Hot Module Replacement (HMR)

    • Issue: Vite/HMR may not hot-reload React components when using Mesh.
    • Fix: Exclude Mesh components from HMR or use a unique key for Livewire components:
      @livewire('counter', key('counter-' . time()))
      

Debugging

  1. Check Mesh Logs Enable debug mode in config/mesh.php:

    'debug' => env('MESH_DEBUG', false),
    

    Logs will appear in Laravel’s log channel.

  2. Inspect Props Use console.log in React to verify props received from Livewire:

    console.log('Props:', props);
    
  3. Network Tab

    • Verify Livewire requests are firing correctly.
    • Check for 403/500 errors in the Network tab (common with CSRF or auth issues).

Config Quirks

  1. Component Mapping

    • Mesh maps Livewire component names to React components by default (e.g., Counter → Counter.jsx).
    • Customize in config/mesh.php:
      'component_map' => [
          'App\Http\Livewire\Counter' => 'react-components/CustomCounter',
      ],
      
  2. Asset Versioning

    • Mesh includes a version hash for React assets. Disable in config/mesh.php if needed:
      'asset_versioning' => false,
      

Extension Points

  1. Custom Renderers Extend MeshComponent to support other frameworks (e.g., Vue, Svelte):

    namespace EthanBarlo\Mesh;
    
    class MeshComponent extends \Livewire\Component
    {
        public static function render(string $componentName, array $props, string $framework = 'react')
        {
            // Custom logic for Vue/Svelte
        }
    }
    
  2. Middleware Add middleware to Mesh requests in AppServiceProvider:

    Mesh::middleware(function ($request, $next) {
        if ($request->wireable) {
            // Custom logic
        }
        return $next($request);
    });
    
  3. Event Listeners Listen for Mesh-specific events (e.g., mesh.rendering):

    Mesh::listen('mesh.rendering', function ($component) {
        // Log or modify component before rendering
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels
wazza/laravel-db-encryption
hokny/laravel-generator
vonsogt/backup
jengo/queues
jeremykenedy/laravel-observability
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums