简体   繁体   中英

How to connect React Component to Laravel Blade

I have a problem adding React to my project. The component is not rendered. This is not SPA project.

I've tried easiest way. I've setup new project with 'laravel new reactexample', next I made 'php artisan preset react' and 'yarn run'. After that I added in welcome blade.php.

Example.js

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

export default class Example extends Component {
    render() {
        return (
            <div className="container">
                <div className="row justify-content-center">
                    <div className="col-md-8">
                        <div className="card">
                            <div className="card-header">
                                Example Component
                            </div>
                            <div className="card-body">
                                I am an example component!
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}

if (document.getElementById('example')) {
    ReactDOM.render(<Example />, document.getElementById('example'));
}

welcome.blade.php, fragmen

<div class="content">
    {...}
    <div id="example"></div>
    {...}
</div>

webpack.mix.js

const mix = require('laravel-mix');

mix.react('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css');

app.js

require('./bootstrap');
require('./components/Example');

Did I miss something in the configuration? What should I do to get rendered component on page?

Ok, I found solutoin. I must add

<script src="{{asset('js/app.js')}}" ></script>

to the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM