Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

432
Views
How to insert Blade code in a React component inside a Blade view?

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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report

0

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:

  1. Set header to let the caller know that it is a JS file.
  2. Set your blade code inside the js. And change the file extension in PHP.
  3. Put the JS file in your view(of your MVC) rename it to .php and put a header on your controller. This should work.
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!