How to use React Router with Laravel?

前端 未结 5 2018
温柔的废话
温柔的废话 2020-12-05 10:01

I needing use React Router with a Laravel project.

But when I create router on the React Router and try access, Laravel<

5条回答
  •  忘掉有多难
    2020-12-05 10:42

    Create a route that maps everything to one controller, like so:

    Route::get('/{path?}', [
        'uses' => 'ReactController@show',
        'as' => 'react',
        'where' => ['path' => '.*']
    ]);
    

    Then in your controller, just show the HTML page that contains the react root document:

    class ReactController extends Controller {
        public function show () {
            return view('react');
        }
    }
    

    Then do everything as normal with react router. Seems to work well for me.


    Update for Laravel 5.5 If your controller only returns a view (like in the example above), you can replace all of the above code with this in your routes file:

    Route::view('/{path?}', 'path.to.view')
         ->where('path', '.*')
         ->name('react');
    

提交回复
热议问题