So I have a Laravel view called homepage.blade.php, it contains the following:
<body>
<div id=root></div>
<script src="./js/app.js"></script>
</body>
Inside app.js:
import React from "react";
import ReactDOM from "react-dom";
import SignUp from "./components/SignUp";
if (document.getElementById("root")) {
ReactDOM.render(<SignUp />, document.getElementById("root"));
}
and inside SignUp.js:
import React from "react";
export default function SignUp() {
return (
<span className="text-xs font-bold uppercase"> Welcome, {!! auth()-> user() -> name !!} </span>
}
The homepage.blade.php is called by a function in a controller, like this:
//inside the function in the Controller.php:
$user = User::create($attributes);
auth()->login($user);
return redirect('/homepage'); // homepage redirects to homepage.blade.php
The problem: I can't insert the line {!! auth()-> user() -> name !!} inside the React component SignUp.js that will be inserted into the homepage.blade.php view.
Question: Is there a way to insert Blade code in a React component? and is there a better way to do this?
CodePudding user response:
You can't use blade in js files. the proper way is, to define variable in blade file using <script></script> tag like this:
<script>
const window.username = '{!! auth()-> user() -> name !!}';
<script src="./js/app.js"></script>
</script>
and then use the defined variable in your app.js file
CodePudding user response:
You can't do it like this. Blade only works on a script which is on MIME-type PHP. You have to load your JS file with .php so that your script can be rendered. Here is how you can do that:
- Set header to let the caller know that it is a JS file.
- Set your blade code inside the js. And change the file extension in PHP.
- Put the JS file in your view(of your MVC) rename it to .php and put a header on your controller. This should work.
