4

I am trying using React ui with laravel. Command I run:

laravel new project
npm i
composer require laravel/ui
php artisan ui react
npm i & npm run dev

After this, when I do php artisan serve it says (About Example.js):

 ERROR: The JSX syntax extension is not currently enabled

I have tried different solutions on google of creating .babelrc and babel.config.js files but nothing removes the error. Can anyone tells why is it so? What is proper configuration of react with laravel?

2 Answers 2

6

If you have installed fresh laravel, it comes with vite.

Since you want to use React, just save the .js files in resources/js as .jsx and then run the npm run dev command again.

They explain it in the document: https://laravel.com/docs/9.x/vite#react

For blade files:

@viteReactRefresh
@vite('resources/js/app.jsx')

For source files: https://laravel.com/docs/9.x/vite#working-with-scripts



Or u can choose another path like this: https://laravel.com/docs/9.x/starter-kits#breeze-and-inertia

Sign up to request clarification or add additional context in comments.

Comments

1

No need babel, you can use vite. This is for Laravel 11

  1. Install react npm install --save-dev @vitejs/plugin-react

  2. Modify vite.config.js

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import react from '@vitejs/plugin-react';
 
export default defineConfig({
    plugins: [
        laravel(['resources/js/app.jsx']),
        react(),
    ],
});
  1. Rename resource/js/app.js to app.jsx

  2. Import react components or react main App.jsx file in to the app.jsx file.

  3. Create blade a file. use <div id="root"></div> to render react app.

<!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>

        <!-- Styles / Scripts -->
        @viteReactRefresh
        @vite('resources/js/app.jsx')
    </head>
    <body class="font-sans antialiased dark:bg-black dark:text-white/50">
       <div id="root"></div>
    </body>
</html>

  1. Go to web.php and add route. (This route will help to render correct page/component in react app instead of returning Laravel 404 not found error)
<?php

use Illuminate\Support\Facades\Route;

Route::get('/{any?}', function () {
    return view('app');
})->where('any', '^(?!api\/)[\/\w\.\,-]*');

  1. Finally php artisan serve npm run dev

Laravel 11 with vite

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.