The process of learning React JS, This post details the use of React with Laravel through a very modern method via the use of Inertia JS.
InertiaJS brings the functionality and ability to build client-side rendered applications and single-page applications without needing client-side routing or an API.
With Inertia you can use common controllers such as seen in Laravel and have a modern UI framework such as React or Vue.
InertiaJS isn’t labelled as being a framework but rather the “glue” between the frontend framework and the backend framework.
In my case Inertia is combining Laravel with React through controllers.
The controller
The controller function uses the Inertia class to render out a component/page with props (the data) passed through.
use Inertia\Inertia; public function show(Book $book): \Inertia\Response { return Inertia::render('Book/Show', [ 'book' => $book ]); }
This is similar to returning a view with data for a blade file in a more classic Laravel project.
If I was not using Inertia then no data could be passed to the page in this way, instead it would need to be accessed by API GET requests.
Book/Show
is simply the file resources/js/Pages/Book/Show.jsx
JSX page
This .jsx page file is found here resources/js/Pages/Book/Show.jsx
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout'; import {Head} from '@inertiajs/inertia-react'; import React from "react"; export default function Show({book}) { return ( <AuthenticatedLayout header={<h2 className="font-semibold text-xl text-gray-800 dark:text-white leading-tight">{book.title}</h2>}> <Head title={book.title + " by " + book.author}></Head> <div className="py-8 px-2 mx-auto max-w-7xl lg:py-10"> <h1 className={'text-2xl font-bold text-gray-800'}>{book.title} ID:{book.id}</h1> {(book.rating >= 7) ? <p className="text-red-500">This book is highly rated</p> : null} </div> </AuthenticatedLayout> ); }
This example uses the AuthenticatedLayout layout and the passed-in prop book can be accessed as an object with properties.
There is also a condition to state that the book is highly rated if it has a rating above or equal to 7.
This is where the convenience of using JSX comes in because the javascript is mixed in with the “DOMS” making it more readable.
The use of imports and a modern IDE makes .jsx file editing incredibly efficient and effective.