I’m coming from a React background working on an existing Laravel project and have figured out a way to use React inside Laravel, and here’s how i”m doing it.
- Inside the resources/js/app.jsx file, I import the React components I’m building.
Inside the React component, at the end of the file I add code like
<code>import React from "react"; import { createRoot } from "react-dom/client";
export function Hello() {
return ( <div> <h1>Hello, World!</h1> </div> );
}
document.addEventListener("DOMContentLoaded",
function () { const rootElement = document.getElementById("hello-root");
if (rootElement) { const root = createRoot(rootElement); root.render(<Hello />); }
});
</code>
<code>import React from "react"; import { createRoot } from "react-dom/client";
export function Hello() {
return ( <div> <h1>Hello, World!</h1> </div> );
}
document.addEventListener("DOMContentLoaded",
function () { const rootElement = document.getElementById("hello-root");
if (rootElement) { const root = createRoot(rootElement); root.render(<Hello />); }
});
</code>
import React from "react"; import { createRoot } from "react-dom/client";
export function Hello() {
return ( <div> <h1>Hello, World!</h1> </div> );
}
document.addEventListener("DOMContentLoaded",
function () { const rootElement = document.getElementById("hello-root");
if (rootElement) { const root = createRoot(rootElement); root.render(<Hello />); }
});
- Inside the views blade template, I add an id=”hello-root” for each blade file so I can insert the react component where I want in the blade file
<code>@section('content')
<main class="main dashboard">
<div class="container-fluid"> </div> <div id="hello-root"></div>
</main>
@endsection
</code>
<code>@section('content')
<main class="main dashboard">
<div class="container-fluid"> </div> <div id="hello-root"></div>
</main>
@endsection
</code>
@section('content')
<main class="main dashboard">
<div class="container-fluid"> </div> <div id="hello-root"></div>
</main>
@endsection
This way I can create a React component individually and insert it where I see fit in whatever blade file I want to associate it with.
Anything wrong with this or something? What do Laravel folk think.