Dev Yego
Dev Yego

Reputation: 553

Can't run a Laravel React project (Inertia)

So, I've been following along this Inertia guide but I can't get the app.blade.php to render the right React component. Or even render just by itself. The /welcome route works but I can't get Inertia to render correctly or even render for that matter. No errors on the console. Here is my resources/js/app.js:

import './bootstrap';

import { createInertiaApp } from '@inertiajs/react'
import { createRoot } from 'react-dom/client'

createInertiaApp({
  resolve: name => {
    const pages = import.meta.glob('./Pages/**/*.jsx', { eager: true })
    return pages[`./Pages/${name}.jsx`]
  },
  setup({ el, App, props }) {
    createRoot(el).render(<App {...props} />)
  },
});

Here is my AppController.php:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Inertia\Inertia;

class AppController extends Controller
{
   public function index() {
     Inertia::render("Index");
   }
}

Here is my resouces/js/Pages/Index.jsx:

import React from 'react';
import { Head } from '@inertiajs/inertia-react';

export default function Index() {
    return (
        <h1>Welcome</h1>
    )
} 

The app.blade.php file:

<!DOCTYPE HTML>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <!-- Fonts -->
        <link rel="preconnect" href="https://fonts.bunny.net">
        <link href="https://fonts.bunny.net/css?family=figtree:400,600&display=swap" rel="stylesheet" />

        @vite('resources/js/app.js')
        @inertiaHead
    </head>
    <body class="antialiased" style="height: 100vh;" id="app">
        @inertia
    </body>
</html>

And finally the routes/web.php file:

<?php

use App\Http\Controllers\AppController;
use Illuminate\Support\Facades\Route;

Route::get('/', [AppController::class, 'index']);

Route::get('/welcome', function () {
    return view('welcome');
});

Upvotes: 0

Views: 393

Answers (1)

Abdul Haseeb Khan
Abdul Haseeb Khan

Reputation: 365

Add a return statement in your AppController in the index function like this

public function index() {
    return Inertia::render("Index");
}

Upvotes: 1

Related Questions