Package for using ReactJS with Laravel

Overview

Code Climate Build Status

react-laravel

With react-laravel you'll be able to use ReactJS components right from your Blade views, with optional server-side rendering, and use them on the client-side with React due to unobtrusive JavaScript.

Installation

V8js dependency

It's important to know that react-laravel has an indirect dependency of the v8js PHP extension.

You can see how to install it here: how to install v8js.

Composer

Set the minimum-stability of your composer.json to dev, adding this:

  "minimum-stability": "dev"

Then run:

  $ composer require talyssonoc/react-laravel:0.11

After that you should add this to your providers at the config/app.php file of your Laravel app:

  'React\ReactServiceProvider'

And then run:

  php artisan vendor:publish

And the react.php file will be available at the config folder of your app.

Usage

After the installation and configuration, you'll be able to use the @react_component directive in your views.

The @react_component directive accepts 3 arguments:

  @react_component(<componentName>[, props, options])

  //example
  @react_component('Message', [ 'title' => 'Hello, World' ], [ 'prerender' => true ])

  // example using namespaced component
  @react_component('Acme.Message', [ 'title' => 'Hello, World' ], [ 'prerender' => true ])
  • componentName: Is the name of the global variable that holds your component. When using Namespaced Components you may use dot-notation for the component name.
  • props: Associative of the props that'll be passed to your component
  • options: Associative array of options that you can pass to the react-laravel:
    • prerender: Tells react-laravel to render your component server-side, and then just mount it on the client-side. Default to true.
    • tag: The tag of the element that'll hold your component. Default to 'div'.
    • html attributes: Any other valid HTML attribute that will be added to the wrapper element of your component. Example: 'id' => 'my_component'.

All your components should be inside public/js/components.js (you can configure it, see below) and be global.

You must include react.js, react-dom.js and react_ujs.js (in this order) in your view. You can concatenate these files together using laravel-elixir.

react-laravel provides a ReactJS installation and the react_us.js file, they'll be at public/vendor/react-laravel folder after you install react-laravel and run:

  $ php artisan vendor:publish --force

For using the files provided by react-laravel and your components.js file, add this to your view:

  <script src="{{ asset('vendor/react-laravel/react.js') }}"></script>
  <script src="{{ asset('vendor/react-laravel/react-dom.js') }}"></script>
  <script src="{{ asset('js/components.js') }}"></script>
  <script src="{{ asset('vendor/react-laravel/react_ujs.js') }}"></script>

If you'll use a different version from the one provided by react-laravel (see composer.json), you got to configure it (see below).

Configurations

You can change settings to react-laravel at the config/react.php file:

  return [
    'source' => 'path_for_react.js',
    'dom-source' => 'path_for_react-dom.js',
    'dom-server-source' => 'path_for_react-dom-server.js',
    'components' => [ 'path_for_file_containing_your_components.js' ]
  ];

All of them are optional.

  • source: defaults to public/vendor/react-laravel/react.js.
  • dom-source: defaults to public/vendor/react-laravel/react-dom.js.
  • dom-server-source: defaults to public/vendor/react-laravel/react-dom-server.js.
  • components: defaults to public/js/components.js. Multiple components files may be specified here.

Your components.js file(s) should also be included at your view, and all your components must be at the window object.

Thanks

This package is inspired at react-rails.

Comments
  • Blade not rendering @react_component

    Blade not rendering @react_component

    Hey,

    This package looks great but I can't get it to work, I have followed the docs line for line but when it comes to including @react_component('Message', [ 'title' => 'Hello, World' ], [ 'prerender' => true ]) inside a blade file it just print it out as if its a string.

    Is this a known fault or something I am doing incorrectly? Like I say I have followed the guide word for word.

    Thanks

    bug 
    opened by joshhornby 45
  • undefined:13: ReferenceError: document is not defined

    undefined:13: ReferenceError: document is not defined

    I'm using gulp to mix all my scripts into public/js/app.js.

    web.php

    Route::get('{slug}', function ($slug) {
        return view('index');
    })->where('slug', '(?![api])([A-Za-z\/\-]+)');
    

    index.blade.php

    <!DOCTYPE html>
    <html>
    <head>
    	<title>React Laravel</title>
    	<meta charset="utf-8">
    	<meta name="viewport" content="width=device-width, initial-scale=1">
    	<link rel="stylesheet" type="text/css" href="{{ asset('css/app.css') }}">
    </head>
    <body>
    	<div id="app">
    		@react_component('Testing', ['initialData' => 'This is prerendered data'])
    	</div>
    	<script type="text/javascript" src="{{ asset('js/app.js') }}"></script>
    </body>
    </html>
    

    My Components

    I only have one component I am using to test things out, which is at root-dir/resources/js/components. then I have my app.js as an entry point for my gulp located at root-dir/resources/js/app.js.

    app.js (entry point)

    import React from 'react';
    import ReactDOM from 'react-dom';
    
    import Testing from './components/Testing';
    
    ReactDOM.render(
    	<Testing/>,
    	document.getElementById('app')
    );
    

    Testing.js (component)

    import React from 'react';
    
    const Testing = React.createClass({
    	render () {
    		console.log(this.props.initialData);
    
    		return (
    			<h1>Hello World</h1>
    		);
    	}
    });
    
    export default Testing;
    

    and When I load my page I get this output error:

    undefined:13: ReferenceError: document is not defined
    

    I've trying using this instead:

    {!! React::render('Testing', ['initialData' => 'Hue']) !!}
    

    but still the same output.

    react.php

    <?php
    
    return [
      'source'     => base_path('node_modules/react/dist/react.min.js'),
      'dom-source' => base_path('node_modules/react-dom/dist/react-dom.min.js'),
      'dom-server-source' => base_path('node_modules/react-dom/dist/react-dom-server.min.js'),
      'components' => base_path('public/js/app.js')
    ];
    

    btw my npm is throwing me this whenever I do npm ls

    npm ERR! peer dep missing: react@^0.14.7, required by [email protected]
    npm ERR! peer dep missing: fbjs@^0.7.2, required by [email protected]
    npm ERR! peer dep missing: react-children@^0.0.3, required by [email protected]
    npm ERR! peer dep missing: react-universal@^0.0.3, required by [email protected]
    
    opened by aprilmintacpineda 12
  • Full example

    Full example

    Excellent work, and appreciate you sharing it.

    I'm new to React JS and recently familiar with Blade.

    It would be great to have a full example on how to work with this component.

    I have searched around the Web for examples using react-laravel, but since this is a fairly new subject specially with Laravel, it would be really helpful to have a full "Hello World" example using Laravel on how to implement this component step by step for creating an UI.

    I'm clear on the installation, that is fine. But after reading the usage instructions, and I'm out of context on where or how to start implementing the blade helper:

    @react_component([, props, options])

    I have so many questions, that I believe only a full example can answer. It would be great to have an example using:

    • How blade template files look like using this component.
    • A before & after transformation from a regular blade view, to one that uses React with your component.
    • A sample view with react components receiving data from Laravel.

    I know this project is very recent, and appreciate you sharing this.

    Thank you.

    help wanted 
    opened by pbreah 10
  • @react_component directive not working?

    @react_component directive not working?

    Laravel 5.1, React-laravel 0.9.1

    Tried on a couple different Laravel apps, both 5.0.* and 5.1. Neither one seemed to render the @react_component directive. Is there a missing step for getting this up and running that's not in the Readme?

    Thanks!

    bug 
    opened by nrcook 9
  • v8js on Laravel Homestead with php7

    v8js on Laravel Homestead with php7

    I just can't get the above combination to work no matter what I try.

    pecl install v8js-0.2.0 fails because "libv8 must be version 3.24.6 or greater"

    pecl install v8js-0.1.3 fails because "ext/standard/php_smart_str.h: No such file or directory"

    All dependencies are installed as far as I can see. Is there any help for this at the moment?

    opened by BeggarsMattM 8
  • Fixed travis tests

    Fixed travis tests

    This should fix the travis tests that appear to be failing. (Checking if its actually going to work as I cant easilly test this. Just assuming this is the reason why it is failing. If its not I'll close this PR and someone else can fix!)

    bug 
    opened by TomCaserta 7
  • Error installing v8js

    Error installing v8js

    I know this is only loosely related to your repo, but I thought getting an issue up would be a good reference for those of us debugging getting v8js installed.

    Most of us use Laravel's Homestead vagrant box environment. I have a newly provisioned VM and, when I run the installation for v8js, I get the below error/output:

    vagrant@homestead:~$ sudo pecl install v8js-beta
    WARNING: channel "pecl.php.net" has updated its protocols, use "pecl channel-update pecl.php.net" to update
    downloading v8js-0.2.0.tgz ...
    Starting to download v8js-0.2.0.tgz (87,387 bytes)
    .....................done: 87,387 bytes
    28 source files, building
    running: phpize
    Configuring for:
    PHP Api Version:         20131106
    Zend Module Api No:      20131226
    Zend Extension Api No:   220131226
    Please provide the installation prefix of libv8 [autodetect] :
    building in /tmp/pear/temp/pear-build-rootqyPDSd/v8js-0.2.0
    running: /tmp/pear/temp/v8js/configure --with-v8js
    checking for grep that handles long lines and -e... /bin/grep
    checking for egrep... /bin/grep -E
    checking for a sed that does not truncate output... /bin/sed
    checking for cc... cc
    checking whether the C compiler works... yes
    checking for C compiler default output file name... a.out
    checking for suffix of executables...
    checking whether we are cross compiling... no
    checking for suffix of object files... o
    checking whether we are using the GNU C compiler... yes
    checking whether cc accepts -g... yes
    checking for cc option to accept ISO C89... none needed
    checking how to run the C preprocessor... cc -E
    checking for icc... no
    checking for suncc... no
    checking whether cc understands -c and -o together... yes
    checking for system library directory... lib
    checking if compiler supports -R... no
    checking if compiler supports -Wl,-rpath,... yes
    checking build system type... x86_64-unknown-linux-gnu
    checking host system type... x86_64-unknown-linux-gnu
    checking target system type... x86_64-unknown-linux-gnu
    checking for PHP prefix... /usr
    checking for PHP includes... -I/usr/include/php5 -I/usr/include/php5/main -I/usr/include/php5/TSRM -I/usr/include/php5/Zend -I/usr/include/php5/ext -I/usr/include/php5/ext/date/lib
    checking for PHP extension directory... /usr/lib/php5/20131226
    checking for PHP installed headers prefix... /usr/include/php5
    checking if debug is enabled... no
    checking if zts is enabled... no
    checking for re2c... re2c
    checking for re2c version... 0.13.5 (ok)
    checking for gawk... no
    checking for nawk... nawk
    checking if nawk is broken... no
    checking for V8 Javascript Engine... yes, shared
    checking for V8 files in default path... not found
    configure: error: Please reinstall the v8 distribution
    ERROR: `/tmp/pear/temp/v8js/configure --with-v8js' failed
    

    I ran pecl channel-update pecl.php.net, but the error persists. Any ideas?

    dependency 
    opened by tommymarshall 6
  • ReactJS Exception Handler

    ReactJS Exception Handler

    Hi,

    At the moment rendering Exceptions are simply dumped to output by ReactJS #35 .

    I've added a very simple handler which simply throws the Exception that's raised so it's caught higher up (Whoops by default). I guess you could do something more clever here and let people pass in their own custom handler for closer control, but it's been ok for now.

    screen shot 2016-04-08 at 20 16 30

    I've also added a small test to confirm that an exception is raised, for example when it can't find the component to render.

    Thanks

    opened by awylie199 5
  • Configuring

    Configuring

    Hi I am new to laravel and to reactJS. I am using gulp to mix all my scripts into one file. What am I suppose to put in these? how am I suppose to configure react-laravel? I have a fresh laravel installation with react-laravel, react-and-friends: react.js, react-dom.js, react-router.js installed via npm.

      return [
        'source' => 'path_for_react.js',
        'dom-source' => 'path_for_react-dom.js',
        'dom-server-source' => 'path_for_react-dom-server.js',
        'components' => [ 'path_for_file_containing_your_components.js' ]
      ];
    
    help wanted 
    opened by aprilmintacpineda 4
  • Syntax error

    Syntax error

    HI

    Do you have any idea why I'm getting this error below when trying to add this in my view @react_component('Message', [ 'name' => 'Hue' ])

    V8Js::compileString():18903: SyntaxError: Unexpected token <

    opened by inkong 4
  • Have you guys ever succeed using this with React addons?

    Have you guys ever succeed using this with React addons?

    I did this:

    ...
    React.createClass({
      mixins: [LinkedStateMixin],
    
      getInitialState() {
    ...
    

    and

    V8Js::compileString():38264: ReferenceError: LinkedStateMixin is not defined
    

    :disappointed_relieved:

    help wanted 
    opened by 18601673727 4
  • React router best practice

    React router best practice

    Hi loading the stuff from laravel routers needs a complete reload each time and redux between the pages will be useless in this case also.So what do you suggest to fix this issues?

    opened by Stevemoretz 0
  • Error Fetching Data in React Native with Laravel as a Back-End

    Error Fetching Data in React Native with Laravel as a Back-End

    Hello Mr./Mrs. Talyssonoc I was wondering if you could help me to solve this error. So I am using laravel as my back-end and I've tested all the method and it works tho. Here's my code for PinjamList.js in RN:

    `import React, { Component } from 'react'; import { View, Text, StyleSheet} from 'react-native'; import PropTypes from 'prop-types';

    export default class PinjamList extends Component {

    static propTypes = { pinjams: PropTypes.array.isRequired }; render() { return ( <View style={styles.pinjamList}> {this.props.pinjams.map((pinjam) => { return ( <View key={pinjam.no_pengajuan}> <Text style={styles.pinjamtext}>{pinjam.ketua_kegiatan} | { pinjam.lab } ) })} ); } }

    const styles = StyleSheet.create({ pinjamList: { flex: 1, flexDirection: 'column', justifyContent: 'space-around', }, pinjamtext: { fontSize: 24, fontWeight: 'bold', textAlign: 'center', } });`

    And this one is js file for fetching the data:

    const URI = 'http://localhost:8000'; export default{ async fetchDataPinjam(){ try{ let response = await fetch(URI + '/api/pinjams'); let responseJsonData = await response.json(); return responseJsonData; } catch(e) { console.log(e); } } }

    And this one is the code for displaying the data on the homepage:

    <View> { this.state.pinjams.length > 0 ? <PinjamList pinjams={this.state.pinjams} /> : <Text>Tidak Ada Peminjaman</Text> } </View>

    But when I try to test it to make sure if its right, this error shown:

    `Network request failed

    • node_modules\react-native\Libraries\vendor\core\whatwg-fetch.js:504:29 in onerror
    • node_modules\event-target-shim\lib\event-target.js:172:43 in dispatchEvent
    • ... 8 more stack frames from framework internals`

    For some reason, I've looked for my DB also with my Laravel. I hope you can help me to figure out this problem because I am still learning in building this react native app. Thank you so much.

    opened by veronicalw 0
  • ComposerAutoloaderInit error

    ComposerAutoloaderInit error

    Once installed and trying to import a component, I get the following error message:

    Cannot declare class ComposerAutoloaderInitac33ba404f5f6ab87abb652f0e9de8bf, because the name is already in use

    opened by fyroc 1
  • Guide for Laravel for REST API only

    Guide for Laravel for REST API only

    Hi there,

    I want to use Laravel for REST API only. I also use react-router so routing is taken care of. However I do need server side rendering, and especially setting the page title server side IF the user has loaded that page with a deep link.

    Is it possible to use react-laravel just for REST API and server side rendering (for initial ReactDOM.render and page title)? Is there a guide for such a thing? (i also use redux)

    (server side page title and meta description is important for sharing on social media like facebook, and server side rendering for web crawlers not supporting js)

    opened by Noitidart 0
  • Minimum Version of Laravel

    Minimum Version of Laravel

    Hello there, i want to know if there's mininum version of the laravel framework that can run with this library?

    My current project laravel's version is 4.2, is it working well in laravel 4.2 ?

    Thankyou so much, best regards

    opened by kenduigraha 1
Releases(v0.11)
Owner
Talysson de Oliveira Cassiano
Talysson de Oliveira Cassiano
Wordpress, ReactJS, GUTENBERG, plugin

Плагін для Wordpress, який розширює функціонал редактора Gutenderg, реалізуючи можливість створювати клієнтську частину використовуючи потужні можливо

turovskiy 1 Nov 25, 2021
Until 2018, Backpack v3 used this Base package to offer admin authentication and a blank admin panel using AdminLTE. Backpack v4 no longer uses this package, they're now built-in - use Backpack/CRUD instead.

Note: This package is only used by Backpack v3. Starting with Backpack v4, everything this package does is included in Backpack/CRUD - one package to

Backpack for Laravel 845 Nov 29, 2022
Backpack v3 used this Base package to offer admin authentication and a blank admin panel using AdminLTE

Until 2018, Backpack v3 used this Base package to offer admin authentication and a blank admin panel using AdminLTE. Backpack v4 no longer uses this package, they're now built-in - use Backpack/CRUD instead.

Backpack for Laravel 845 Nov 29, 2022
⚡️ This package provides a wonderful PHP skeleton to start building your next package idea.

This package provides a wonderful PHP Skeleton to start building your next package idea. Requires PHP 8.0+ ⚡️ Create your package using Composer: comp

Nuno Maduro 383 Dec 20, 2022
High scalable boilerplate for Laravel - Vue using laravel-mix.

Why use this ? This boilerplate make developer easier to make monolith Laravel project which integrated with Vue.js and vue-router as default front-en

Carvel Saputra Martaloho 5 Sep 21, 2022
:elephant: A Laravel 6 SPA boilerplate with a users CRUD using Vue.js 2.6, GraphQL, Bootstrap 4, TypeScript, Sass, and Pug.

Laravel Vue Boilerplate A Laravel 6 Single Page Application boilerplate using Vue.js 2.6, GraphQL, Bootstrap 4, TypeScript, Sass and Pug with: A users

Alefe Souza 533 Jan 3, 2023
It's a template for using Temporal with Laravel

Temporal Integration with Laravel Make sure you have PHP 7.4 and laravel 8.* , or higher, installed. Temploral PHP SDK is available as composer packag

Improwised Technologies Pvt. Ltd. 14 Nov 5, 2022
Basic Crud Generator (With Code Files, like GII (YII2)) Using Laravel, Livewire and Tailwind CSS

LiveCrud Live Crud Generator. This package generates Basic Crud with Livewire. Features Generate Complete Crud With Livewire Component and Blade Files

Ritesh Singh 28 Oct 12, 2022
A Laravel 8 and Vue 3 SPA boilerplate using tailwind styling and sanctum for authentication :ghost:

Laravel Vue Sanctum SPA Laravel and vue spa using tailwind (laravel/ui looks) for styling and sanctum for authentification Features Laravel 8 Vue + Vu

Hijen EL Khalifi 62 Dec 5, 2022
This project is for developing an blog_api using laravel

Blog Api A TDD implementation of a weblog RESTful API. This project is a REST api implementation of my other project laravel with more features. featu

sina shariati 6 Nov 8, 2021
Laravel wrapper of LightnCandy for using Handlebars (and Mustache) templates

Laravel Handlebars This package allows you to use Handlebars (and Mustache) templates with Laravel. You can integrate Handlebars templates into Blade

null 37 Jul 26, 2022
A simple starter kit for using TypedCMS with the Laravel framework.

TypedCMS Starter Kit for Laravel Our stater kits are tailored solutions for each platform, unlike the simple API wrappers offered by other vendors. Th

TypedCMS 1 Nov 20, 2021
Create read update & delete using Laravel 8 with Login & register

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Fawwaz Bayureksa 1 Feb 4, 2022
👔 Enterprise Web application starter kit or template using Laravel

Laravel Enterprise Starter Kit (LESK) Description LESK, is a template project based on the Laravel LTS, combining a set of features that can kick star

Sebastien Routier 1 Dec 31, 2020
An opinionated Laravel setup using my favourite tools

Opinionated Laravel Template This is a template I use when starting a new Laravel project. It is opinionated and uses the conventions I prefer to work

Luke Downing 42 Nov 26, 2022
A template for web development using Laravel, Inertia and Svelte

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Atikur Rahman Chitholian 0 Dec 26, 2021
An open source blog, made using Laravel, Inertia.js, and React.js. Also a learning repository.

Blog An open source Laravel-based blog. Still in progress, will be updated regularly as I wrote articles on my blog. Configurations Shared-hosting, an

Aghits Nidallah 8 Dec 6, 2022
Creating authentication using sanctum, laravel and VUE

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Mohd Aminuddin 1 May 11, 2022
A Laravel 5 package that switchs default Laravel scaffolding/boilerplate to AdminLTE template and Pratt Landing Page with Bootstrap 3.0

AdminLTE template Laravel package A Laravel package that switch default Laravel scaffolding / boilerplate to AdminLTE template with Bootstrap 3.0 and

Sergi Tur Badenas 1.8k Jan 3, 2023