How To Integrate CakePHP with React

CakePHP’s View is weak compared to it’s Model and Control framework. Because of this, people often use React as a supplement or replacement to the frontend. This guide will provide information on how you can use React alongside CakePHP.

Embed React Components inside Cake’s View Templates

Store all of your React components inside a separate folder. In my case, they will live inside /src/React/components. Each embeddable React component will attach itself to the DOM.

//?????? ???/?????/??????????/

?????? ????? ???? '?????';
?????? ???????? ???? '?????-???';

???????? ???????????????????() {
	?????? (
		<??>????? ?????</??>
	);
}
????????.??????(<???????????????????/>, ????????.??????????????('?????????'));

Note: The parentTag will be the bridge between React and CakePHP.

Configure webpack.config.js to compile each .jsx file into a JavaScript file. The code below compiles src/React/components/embedable-components.jsx to /webroot/js/embeddable-component.jsx.

// ?????? ???????.??????.??

????? ???? = ???????('????');

??????.??????? = {
   ?????: {
      ?????????_?????????:
          ????.???????(__???????, "???", "?????", "??????????", "?????????-?????????.???")
   },
   ??????: {
       ????: ????.???????(__???????, "???????", "??"),
	    ????????: '[????].??'
        },
  ??????: { /** ???? ??? ???????? ????? ??????????? **/}
};

Once we build the app, components inside webroot will be accessible inside Cake’s view templates and can easily be embedded:

<??? ??="?????????">
	<???? 
		// ???? ?? ??? ?????? ??????? ??????? ??? ???????
		???? $????->????->??????('?????????_?????????.??');
	?>
</???>

Note: Ensure that the parentTag appears before the call to the script import.

React as Single-Page Frontend with CakePHP

React Router is a library that can control the browser’s navigation and history interface. We can use React Router instead of CakePHP’s backend routing. However, we still need to tell CakePHP to load the initial page where our React app lives. 

// ?????? ??????/??????.???
$???????->???????('/*', ['??????????' => '?????', '??????' => '????']);

The following code disables Cake’s automatic template rendering via URL and routes all URL requests to a single webpage we’ve created called main

Moving forward, we still need to make sure that Cake’s REST APIs are accessible. The following code below will route your URLs that are prefixed with `api/` to the generic route.

??? ????\???????\?????\???????????;

$??????->?????('/???', ???????? (???????????? $??????) {
    $??????->?????????(???????????::?????);
});

Following the steps in the section above you can embed your entire React application in the single template rendered by PagesController::main().

References: