Coder Social home page Coder Social logo

react-php-v8js's Introduction

React-PHP-V8Js

React-PHP-V8Js is an experimental library that uses the power of Facebook's React library to render UI components on the server-side with PHP as well as on the client.

Prerequisites

For a walkthrough how to setup V8Js PHP extension, use the links below:

Usage

// the library
$react_source = file_get_contents('/path/to/build/react.js');
// all custom code concatenated
$app_source = file_get_contents('/path/to/custom/components.js');

$rjs = new ReactJS($react_source, $app_source);
$rjs->setComponent('MyComponent', array(
  'any'   =>  1,
  'props' =>  2
  )
);

/// ...

// print rendered markup
echo '<div id="here">' . $rjs->getMarkup() . '</div>';

/// ...

// load JavaScript somehow - concatenated, from CDN, etc
// including react.js and custom/components.js

// init client
echo '<script>' . $rjs->getJS("#here") . '</script>'; 

/// ...

// repeat setComponent(), getMarkup(), getJS() as necessary
// to render more components

License

BSD License for React-PHP-V8Js

Copyright (c) 2014, Facebook, Inc. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  • Neither the name Facebook nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

react-php-v8js's People

Contributors

jbroadice avatar stoyan avatar talyssonoc avatar teameh avatar toretto460 avatar zpao avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-php-v8js's Issues

Issue new release

The current stable (1.0.0) is behind the master branch with some important commits that fixes deprecation warnings like "Warning: React.renderToString is deprecated. Please use ReactDOMServer.renderToString from require('react-dom/server') instead.". A workaround is using dev-master and minimum-stability:dev which makes my skin itch...

The relevant commit: 05637db

react-php-v8js with React 16.1.1

Does react-php-v8js work with the newer version of react?

When I try to make it work with 16.1.1 and following code:

class Table extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    var rows = this.props.data.map(function (row) {
      var cells = row.map(function(cell) {
        return <td>{cell}</td>;
      });
      return <tr>{cells}</tr>;
    });
    return (
      <table>
        <tbody>{rows}</tbody>
      </table>
    );
  }
}

I get this Error:
V8Js::compileString():1007: TypeError: Super expression must either be null or a function, not undefined

How dose Facebook use react for server-side-render?

I noticed that on the Facebook website, there are react components. I think it should be rendered on the server side. But Facebook use php do the render job, so how do they implement the architecture? Do they use the react-php-v8js way?

Warnings

When I run the example I get the following warnings:

Warning: React.render is deprecated. Please use ReactDOM.render from require('react-dom') instead.warning @ react.js:18769
react.js:18769 Warning: render(): Target node has markup rendered by React, but there are unrelated nodes as well. This is most commonly caused by white-space inserted around server-rendered markup.warning @ react.js:18769
react.js:18769 Warning: Each child in an array or iterator should have a unique "key" prop. Check the top-level render call using <tr>. See https://fb.me/react-warning-keys for more information.warning @ react.js:18769
react.js:18769 Warning: Each child in an array or iterator should have a unique "key" prop. Check the top-level render call using <tbody>. See https://fb.me/react-warning-keys for more information.warning @ react.js:18769

How to fix ?

Syntax error : Unexpected token >

HI

Do you have any idea why I'm getting this error below when trying to add this in example.php

include '../ReactJS.php';

$rjs = new ReactJS(
  // location of React's code
  file_get_contents('https://fb.me/react-15.2.0.js'),
  // app code
  file_get_contents('./src/table.js')
);
print_r($rjs);die;

V8Js::executeString():20225: SyntaxError: Unexpected token >

I found some error when "npm run make"

0 info it worked if it ends with ok
1 verbose cli [ 'C:\Program Files\nodejs\node.exe',
1 verbose cli 'C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js',
1 verbose cli 'run',
1 verbose cli 'make' ]
2 info using [email protected]
3 info using [email protected]
4 verbose run-script [ 'premake', 'make', 'postmake' ]
5 info premake [email protected]
6 info make [email protected]
7 verbose unsafe-perm in lifecycle true
8 info [email protected] Failed to exec make script
9 verbose stack Error: [email protected] make: npm run make-dev && npm run make-min && npm run make-table
9 verbose stack Exit status 1
9 verbose stack at EventEmitter. (C:\Program Files\nodejs\node_modules\npm\lib\utils\lifecycle.js:213:16)
9 verbose stack at EventEmitter.emit (events.js:110:17)
9 verbose stack at ChildProcess. (C:\Program Files\nodejs\node_modules\npm\lib\utils\spawn.js:24:14)
9 verbose stack at ChildProcess.emit (events.js:110:17)
9 verbose stack at maybeClose (child_process.js:1015:16)
9 verbose stack at Process.ChildProcess._handle.onexit (child_process.js:1087:5)
10 verbose pkgid [email protected]
11 verbose cwd C:\Users\supachai.w\Desktop\react\react-php-v8js\example
12 error Windows_NT 6.3.9600
13 error argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "run" "make"
14 error node v0.12.5
15 error npm v2.11.2
16 error code ELIFECYCLE
17 error [email protected] make: npm run make-dev && npm run make-min && npm run make-table
17 error Exit status 1
18 error Failed at the [email protected] make script 'npm run make-dev && npm run make-min && npm run make-table'.
18 error This is most likely a problem with the react-php-v8js package,
18 error not with npm itself.
18 error Tell the author that this fails on your system:
18 error npm run make-dev && npm run make-min && npm run make-table
18 error You can get their info via:
18 error npm owner ls react-php-v8js
18 error There is likely additional logging output above.
19 verbose exit [ 1, true ]

How do I solve this issue, Thank.

usage with gulp?

this is the usage example you provided:

// the library
$react_source = file_get_contents('/path/to/build/react.js');
// all custom code concatenated
$app_source = file_get_contents('/path/to/custom/components.js');

$rjs = new ReactJS($react_source, $app_source);
$rjs->setComponent('MyComponent', array(
  'any'   =>  1,
  'props' =>  2
  )
);

/// ...

// print rendered markup
echo '<div id="here">' . $rjs->getMarkup() . '</div>';

/// ...

// load JavaScript somehow - concatenated, from CDN, etc
// including react.js and custom/components.js

// init client
echo '<script>' . $rjs->getJS("#here") . '</script>'; 

/// ...

// repeat setComponent(), getMarkup(), getJS() as necessary
// to render more components

I'm not sure if the following lines will be applicable if I am using gulp and laravel-elixir to mix all my scripts into a single file.

$app_source = file_get_contents('/path/to/custom/components.js');
echo '<script>' . $rjs->getJS("#here") . '</script>';

setTimeout is not defined

Hi,

I keep getting this error:

V8Js::compileString():78458: ReferenceError: setTimeout is not defined

I am not sure where to start to solve this issue.

getMarkup() is returning the literal JSX markup instead of the HTML markup.

The method getMarkup() returns the literal JSX component, instead of the compiled HTML markup like you would expect.

Here's the code that I am running:

$react = new ReactJS($reactSource, $appSource);

$react->setComponent('Hello', ['name' => 'joe']);

$markup = $react->getMarkup();

echo $markup;

And here's what the value of $markup is after I call the getMarkup() method.

<Hello name="joe" data-reactroot="" data-reactid="1" data-react-checksum="2146833468"></Hello>

I am currently running PHP7.0 on Ubuntu 15.10 with the latest version of V8, and with V8JS for PHP7.0. I should also note the I am using the following react files as the source for react: react.min.js, react-dom.min.js, and react-dom-server.min.js.

EDIT 1: Turns out it only renders the literal JSX markup when I pass the component name as a string literal like so: "'Hello'", whenever I pass the the component name to the method like so: 'Hello' just as a regular string it raises this error:

V8Js::compileString():1: ReferenceError: Hello is not defined

Stating that the component is undefined.

EDIT 2: Here's the code for the React component I'm trying to render:

import React from "react";

class Hello extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div>Hello {this.props.name}!</div>
        );
    }
}

EDIT 3: I managed to fix the issue by adding global.Hello = Hello; to the end of the JS file.

$this->v8->executeString() needs to be echoed in ReactJS.php

I did a cURL on the page I set up to verify that PHP had indeed echoed both the markup and the JS, and what I found was that the JS was outputted, but the markup didn't get generated until the page loaded (curl request resulted in <div id="page"></div>). When I inspected the table element, the data was there, so the JS initialized it. If you view source immediately, you'll see an empty #page as well.

Since you have an output buffer in ReactJS::getMarkup(), you have to echo, like so:

ob_start();
*echo* $this->v8->executeString($js);      
return ob_get_clean();

Once I added the echo and did a cURL request, I noticed that the markup was actually there before the JS had a chance to render it.

I'd put in a pull request, but I just wanted to verify that this was intended behavior and I wasn't missing anything.

Render Children

Possibly allow for the rendering of child components so that wrappers aren't required.

I already have a solution to this.

Any boilerplate?

Hi,
is there any examples?
What exactly should I pass as $react_source? react.js from https://github.com/facebook/react/releases? Or webpack'ed chunk with react and react-dom?
What is $app_source? Entrance point? Should it be webpack bundle? Or plain components scripts? Should they be transpiled with babel first?

Some boilerplate project needed.
At the moment I can't start work by any means.

No clear way to access ReactDOMServer in React ^0.14.0

Since the separation of ReactDOM and ReactDOMServer since React 0.14 there is no clear way to access from ReactDOMServer after loading react-dom.js

In an earlier issue, I posted enough code to load ReactDom into the ReactJS class but I don't see a way to write the equivalent of the following commonJS require in php…

import ReactDOMServer from 'react-dom/server' 

cc @stoyan

Issues with react-select

Hi,

I am having issues with react-select package on SSR. This is one of the common components to use. When I add it on SSR with react-php-v8js I get this error:
V8Js::compileString():38055: TypeError: Cannot read property 'userAgent' of undefined

I was wondering maybe someone had this issue and managed to solve it via config or etc.
Thanks in advance for any help.

Trouble getting a simple component to render

Error is as follows:

V8Js::compileString():19434: ReferenceError: module is not defined

PHP Test file is as follows:

include('../vendor/autoload.php');

$reactSource = file_get_contents('../node_modules/react/dist/react.js');
$appSource = file_get_contents('../app/Resources/js/components/Test.js');

$rjs = new \ReactJS($reactSource, $appSource);
$rjs->setComponent('Test', []);

echo '<div id="here">' . $rjs->getMarkup() . '</div>';

Javascript Component is as follows:

const Test = React.createClass({
    render: function() {
        return React.createElement('div', {}, 'Hello, World')
    }
})

module.exports = Test;

Are you able to shed any light as to why module is not available here? Thanks for your time.

Uncaught ReferenceError: Component is not defined

How can I use Browserify or webpack to compile a es6 script that works with reach-php-v8js? I have tried the following but it looks like the js string produced by $rjs->getJS("app", "GLOB"); fails to access the component ItemPage in build.js which isn't in the global scope.

ReactDOM.render(React.createElement(ItemPage, {"value":"something"}), app);

item_page.js

class ItemPage extends React.Component {
    render(){
        return <div>{this.props.value}</div>
    }
}

After transpiling the es6 code into es5 with browserify, build.js by this command,

browserify item_page.js -o /js/build.js -t [ babelify --presets [ es2015 react ] ]

it ends up like this

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var ItemPage = function (_React$Component) {
    _inherits(ItemPage, _React$Component);

    function ItemPage() {
        _classCallCheck(this, ItemPage);

        return _possibleConstructorReturn(this, Object.getPrototypeOf(ItemPage).apply(this, arguments));
    }
    _createClass(ItemPage, [{
        key: "render",
        value: function render() {
            return React.createElement(
                "div",
                null,
                "Testing"
            );
        }
    }]);

    return ItemPage;
}(React.Component);

},{}]},{},[1]);

Error in Chrome:

Uncaught ReferenceError: ItemPage is not defined

Html output

<html>
<head>
    <title>React page</title>
    <!-- css and stuff -->
</head>
<body>
<!-- render server content here -->
<div id="app"><?php echo $rjs->getMarkup(); ?></div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.0/react.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.0/react-dom.min.js"></script>
<script src="/js/build/build.js"></script>
<script>
    ReactDOM.render(React.createElement(ItemPage, {"value":"something"}), app);</script>
   <!-- This is the result of echo $rjs->getJS($mainId, "GLOB"); -->
</script>
</body>
</html>

Cake php | pushing data JSON into the component | reactDOMServer

We've been trying to use this with Cake php. So far I've had no luck in pushing the json data into the component and then render it. The code looks somewhat like this:

<?php
App::uses('AppController', 'Controller');
include '../../vendor/reactphp/ReactJS.php';
class ReactController extends AppController {
 public function index() {
        $testJSON=[
          [
              'imageUrl' => 'https://scontent.cdninstagram.com/hphotos-xfa1/t51.2885-15/s640x640/sh0.08/e35/12132892_1390180737947878_1933929151_n.jpg',
              'caption' => '#hiking #waterfall #stream #beautiful #nature #fun #photooftheday #sightseeing #travel #newhampshire #whitemountains #wonderful'
          ],
          [
              'imageUrl' => 'https://scontent.cdninstagram.com/hphotos-xaf1/t51.2885-15/s640x640/sh0.08/e35/12135352_909678639126847_907565337_n.jpg',
              'caption' => 'An osage orange tunnel made as boundaries when fences couldnt be made to keep people off local farms. #osage #tunnel #nature #hiking #tree #ohio #sugarcreek #sugarcreekmetropark #natgeo #natgeotravel #explore'
          ]
        ];
        $rjs = new ReactJS(
        file_get_contents('https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react.js'), // location of React's code
    file_get_contents(FULL_BASE_URL.'/js/instagramFeed-raw.js'));

        $rjs->setComponent('PictureCard', json_encode($data));
        $this->set('markup',$rjs->getMarkup());
    }
}

?>

index.ctp looks like this

<h1>Test</h1>
<div id="here"><?php echo $markup;?></div>

The js file looks like

"use strict";

var PictureCard = React.createClass({
  displayName: "PictureCard",

  loadPicturesFromServer: function loadPicturesFromServer() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: (function (data) {
        // console.log(data);
        this.setState({ data: data });
        // console.log(this.state);
      }).bind(this),
      error: (function (xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }).bind(this)
    });
  },
  getInitialState: function getInitialState() {
    return { data: [] };
  },
  componentDidMount: function componentDidMount() {
    this.loadPicturesFromServer();
    // setInterval(this.loadPicturesFromServer, this.pollInterval);
  },
  render: function render() {
    var image = this.state.data.map(function (image, index) {
      return(
        // `key` is a React-specific concept and is not mandatory for the
        // purpose of this tutorial. if you're curious, see more here:
        // http://facebook.github.io/react/docs/multiple-components.html#dynamic-children
        React.createElement(
          "div",
          { key: index },
          React.createElement(
            "a",
            { href: image.imageUrl },
            React.createElement("img", { key: image.imageUrl, src: image.imageUrl })
          ),
          React.createElement(
            "h1",
            { key: image.caption },
            " ",
            image.caption,
            " "
          )
        )
      );
    });
    return React.createElement(
      "div",
      { className: "pictureCard" },
      image
    );
  }
});

I want to use ReactDOMServer.renderToString with this, but there's no way that I can currently do that.
cc @stoyan

Register in packagist

Hi @zpao ,

I am really sorry to bother you with that.
I have a final request to ask you. Is this possible to publish it on packagist ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.