Skip to content

Instantly share code, notes, and snippets.

@searleb
Last active September 10, 2017 21:55
Show Gist options
  • Save searleb/e0adada208568fe5be56fb4805ed10e6 to your computer and use it in GitHub Desktop.
Save searleb/e0adada208568fe5be56fb4805ed10e6 to your computer and use it in GitHub Desktop.
Setting up React with Laravel

Setting up React with Laravel

This guide will help you get a starting point for implementing React into a default install of Laravel v5.3.

Install React

cd application
npm install --save react react-dom

Gulp file

// require webpack
require('laravel-elixir-webpack-official');

// configure webpack
Elixir.webpack.mergeConfig({
   babel: {
      presets: [
         'react',
         'es2015',
         'stage-0',
      ]
   }
})

// add webpack - app.scss and app.js are found here:
// application/resources/assets/sass/app.scss
// application/resources/assets/js/app.js
// This folder sturcture a Laravel default
elixir(mix => {
   mix.sass('app.scss')
   .webpack('app.js');
});

To compile run from /application:

gulp

or for continuous compiling

gulp watch

Rendering React in a Blade template

  • Create your React components in:
application/resources/assets/js/
  • Create or update layout.blade.php in application/resources/views to contain a @yield('react') directive:
<body>
    @yield('content')
    @yield('react')
</body>
  • Create a page route in application/routes/web.php and serve a blade view:
Route::get('react', function () {
    return view('react-counter');
});
  • Create the blade view containing a div with an id and include the bundled app.js by injecting the script into our 'react' yield area:
@extends('layout')
@section('content')
    <div id="counter-app"></div>
@endsection
@section('react')
    <script src="/js/app.js"></script>
@endsection
  • Create a React render method in application/resources/assets/js/app.js targeting the div id ie #counter-app:
import React from 'react'
import ReactDOM from 'react-dom'
import Counter from './Counter'
ReactDOM.render(
   <Counter />,
   document.getElementById('counter')
)
  • Run gulp
  • Visit your route in a browser and you should see your new React component 😎
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment