Laravel5.5でもVue.jsっぽくReact.jsを部分的に導入する


背景

タイトルまんま

導入

$ composer create-project --prefer-dist laravel/laravel react-laravel "5.5"
$ cd react-laravel
$ php artisan preset react
$ npm install && npm run dev

ここでコンパイルまでは行って、サンプルまで表示できる。

LaravelからReact.jsに変数を渡す

welcome.blade.php
.
.
.
    <body>
        <div class="flex-center position-ref full-height">
            <div id="example" title="title"></div>
        </div>

        <script src="{{ asset('js/app.js')}}"></script>
    </body>
Example.js
import React from 'react';
import { render } from 'react-dom';

const Example = ({ title }) => (
    <div className="container">
        <div className="row">
            <div className="col-md-8 col-md-offset-2">
                <div className="panel panel-default">
                    <div className="panel-heading">Example Component</div>

                    <div className="panel-body">
                        {title}
                    </div>
                </div>
            </div>
        </div>
    </div>
);


const Element = document.getElementById('example');
if (Element) {
    const title = Element.getAttribute('title');
    render(<Example title={title} />, document.getElementById('example'));
}

いざコンパイルと画面表示

$ npm run dev
$ php artisan serve

参考

Laravel bladeからReactコンポーネント(Material UI)にバリデーションエラーメッセージを渡してみる