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: