Weave Code
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

React With Laravel Blade Laravel Package

ghazniali95/react-with-laravel-blade

Generate React components for use in Laravel Blade templates. Provides an Artisan command to scaffold components, optionally with props/args, for Laravel apps using Vite + React. Add generated components to vite.config.js for building.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require ghazniali95/ReactWithLaravelBlade
    npm install react react-dom @vitejs/plugin-react
    
  2. Configure Vite (if not already set up):

    • Ensure vite.config.js includes @vitejs/plugin-react:
      import { defineConfig } from 'vite';
      import laravel from 'laravel-vite-plugin';
      import react from '@vitejs/plugin-react';
      
      export default defineConfig({
        plugins: [
          laravel({
            input: ['resources/js/app.js'],
            refresh: true,
          }),
          react(),
        ],
      });
      
  3. Generate a React Component:

    php artisan create:reactComponent MyComponent
    
    • This creates a Blade file (resources/views/components/MyComponent.blade.php) with embedded React JSX.
  4. Use in Blade:

    @reactComponent('MyComponent', ['prop1' => 'value1', 'prop2' => 'value2'])
    
  5. Run Dev Servers:

    npm run dev
    php artisan serve
    

First Use Case

Create a simple counter component:

php artisan create:reactComponent Counter --arg=initialCount

Edit the generated Blade file (resources/views/components/Counter.blade.php) to include JSX:

<div id="counter-root"></div>

<script type="text/babel">
  const { useState } = React;
  const Counter = ({ initialCount }) => {
    const [count, setCount] = useState(initialCount);
    return (
      <div>
        <p>Count: {count}</p>
        <button onClick={() => setCount(count + 1)}>Increment</button>
      </div>
    );
  };
  ReactDOM.render(<Counter initialCount={@json($initialCount)} />, document.getElementById('counter-root'));
</script>

Use it in a Blade template:

@reactComponent('Counter', ['initialCount' => 0])

Implementation Patterns

Workflows

  1. Component Development:

    • Generate components via Artisan:
      php artisan create:reactComponent [Name] --arg=prop1,prop2
      
    • Edit the generated Blade file to include JSX and logic.
    • Use @reactComponent directive in Blade to render the component with props.
  2. Props Handling:

    • Pass props as an associative array:
      @reactComponent('UserCard', [
        'user' => $user,
        'isAdmin' => true,
      ])
      
    • Access props in JSX via destructuring:
      const UserCard = ({ user, isAdmin }) => { ... }
      
  3. State Management:

    • Use React hooks (e.g., useState, useEffect) directly in Blade-embedded JSX.
    • Example: Form handling with local state:
      const [formData, setFormData] = useState({ name: '' });
      const handleSubmit = (e) => { e.preventDefault(); ... };
      
  4. Styling:

    • Use Tailwind CSS or CSS modules in Blade:
      <div class="p-4 bg-gray-100">
        @reactComponent('MyComponent')
      </div>
      
    • Import CSS in Vite for React-specific styles.
  5. API Integration:

    • Fetch data in useEffect:
      useEffect(() => {
        fetch('/api/data')
          .then(res => res.json())
          .then(data => setData(data));
      }, []);
      

Integration Tips

  • Laravel Mix/Vite: Ensure Vite is configured to process .blade.php files. Add to vite.config.js:
    laravel({
      input: ['resources/js/app.js', 'resources/views/**/*.blade.php'],
    }),
    
  • TypeScript Support: Add @vitejs/plugin-react-swc for TypeScript:
    import react from '@vitejs/plugin-react-swc';
    
  • Shared Logic: Extract reusable React logic into separate JS files and import them in Blade:
    import { MyHook } from '/js/hooks/MyHook.js';
    
    <script type="module" src="/js/hooks/MyHook.js"></script>
    

Gotchas and Tips

Pitfalls

  1. Vite Hot Module Replacement (HMR):

    • HMR may not work seamlessly with Blade-embedded React. Restart Vite (npm run dev) if changes aren’t reflected.
    • Avoid inline JSX in Blade for complex logic; move to separate .jsx files.
  2. Prop Serialization:

    • Complex objects (e.g., Eloquent models) may not serialize correctly. Use @json:
      @reactComponent('Component', ['user' => @json($user->toArray())])
      
  3. Dependency Conflicts:

    • Ensure react and react-dom versions match between Vite and Blade. Use npm ls react to check.
  4. Build Process:

    • Components must be manually added to Vite’s input array in vite.config.js for production builds:
      input: [
        'resources/js/app.js',
        'resources/views/components/**/*.blade.php',
      ],
      
  5. Caching:

    • Blade caches may interfere with React updates. Clear caches:
      php artisan view:clear
      npm run build
      

Debugging

  • Console Errors: Check browser console for React errors. Blade-embedded JSX may fail silently if syntax is incorrect.
  • Artisan Command Issues: Verify the create:reactComponent command is registered in app/Console/Kernel.php:
    protected $commands = [
       \Ghazniali95\ReactWithLaravelBlade\Console\Commands\CreateReactComponent::class,
    ];
    
  • Vite Dev Server: Ensure Vite is running and listening on the correct port (default: 5173). Blade may not auto-refresh React changes.

Tips

  1. Component Organization:

    • Group Blade components in resources/views/components/ and use @include for shared layouts:
      @include('components.layouts.app', [
        'content' => @reactComponent('MyComponent')
      ])
      
  2. Environment-Specific Builds:

    • Use Vite’s mode to conditionally load components:
      // vite.config.js
      export default defineConfig(({ mode }) => ({
        plugins: [
          react(),
          laravel({
            input: mode === 'production'
              ? ['resources/js/app.js']
              : ['resources/js/app.js', 'resources/views/**/*.blade.php'],
          }),
        ],
      }));
      
  3. Testing:

    • Test React components in isolation using Jest or React Testing Library. Mock Blade props:
      // TestComponent.test.jsx
      test('renders with props', () => {
        const props = { initialCount: 0 };
        render(<Counter {...props} />);
        expect(screen.getByText('Count: 0')).toBeInTheDocument();
      });
      
  4. Performance:

    • For heavy components, lazy-load with React.lazy:
      const LazyComponent = React.lazy(() => import('./LazyComponent.jsx'));
      
    • Use Suspense for fallback UI:
      <Suspense fallback={<div>Loading...</div>}>
        <LazyComponent />
      </Suspense>
      
  5. Extending the Package:

    • Customize the Artisan command template in vendor/ghazniali95/react-with-laravel-blade/src/Console/Commands/CreateReactComponent.php.
    • Add Blade directives by publishing the package’s config:
      php artisan vendor:publish --provider="Ghazniali95\ReactWithLaravelBlade\ServiceProvider"
      
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle