Hello everyone and thank you for clicking on this article. 🙂
There's a debate that's been raging for a long time in the developer community, namely: PHP vs Javascript.
Leaving aside the relevance of such debates (each techno having its pros and cons), today I've decided to perform the complete heresy. 😛
Let's take a look at how to integrate React (a Javascript Front library) into a Symfony project (PHP back-end framework). 😀
"Isn't that a bit counter-intuitive?"
Not necessarily, and you're about to see why.
Here again, as in the initial debate, it's all a matter of taste, choice and relevance to a project's needs.
For my part, I was faced with a dilemma when I wanted to create a new micro-SAAS:
As you probably know, Symfony has been using Webpack as well as npm or yarn to manage the front-end of its applications for several versions now. This will make things easier for us, since React uses the same method to initialize its projects and manage its dependencies.
So we'll initialize a Symfony project as usual and then, once done, install the React dependencies directly into the same project. For this, there's an official documentation explaining how to add React as part of an existing page.
Once you've followed these steps, you can consider React installed and ready for use in your project.
"Yes, but I'm still seeing twig there in my Symfony so it's not finished."
Exactly, the connection between Symfony and React is now missing. 😛
To do this, we'll first have to edit the tsconfig.json file and add :
This will avoid any build errors due to the context in which React will run.
We also need to edit the webpack.config.js file and uncomment the following lines:
Voilà! 🎉
"What? That's it? React works here?"
And yes! 😀 How do you test this? By editing your main twig file like this:
Then in the assets of your Symfony project adding a JS file as usual which will contain :
Now you can render any React component in Home and you'll see it appear on the page leading to your Twig.
I've drawn a diagram to show you exactly how it all works:
That's it, pretty simple isn't it? 😛
As I said earlier, I made this stack combination for my own personal needs. So my advantages won't be the same for everyone, but here it was all about :
@mui/material
, for example).The disadvantages are :
To conclude this article, we can realize that a lot is still possible in development, even with very different technologies and usually coming from opposite universes.
Don't forget that huge platforms like Facebook or Google run on multiple languages and multiple connections between them. Sometimes you don't want to lock yourself into an ecosystem when you could benefit from much more efficient tools by picking and choosing.
That's what I wanted to show here in my experiment. 🙂
On that note, I'm going back to TypescriPHP and I'll see you soon! 😛