Symfony ReactJS using Encore

February 7, 2018 | 2 Comments | Programming | reactjs symfony

ReactJS is quite popular front-end framework and it can be easily integrated with Symfony. In this guide, we will setup Symfony ReactJS using Symfony Component –  Encore

Overview

Encore is Npm package based on Webpack which helps us to build assets. It’s replacement for old Symfony Assetic component. You should have NodeJS 6+ and Npm installed on you PC to use encore.

ReactJS is frontend framework created by Facebook and widely used in web development. It’s most loved framework by developer according StackOverflow Survery 2017.

Symfony 4 Installation

Let’s follow official documentation and create empty Symfony 4 project. You need PHP7 and Composer installed. Skip this step if you alredy have Symfony installed.

composer create-project symfony/website-skeleton react
cd react
composer require server --dev
php bin/console server:run
Last two commands needed only if you want to use built-in PHP server.

Installing Encore

If you’re already have webpack.config.js after Symfony installation then you can skip this step, just run npm install . You’re already have Encore installed. If not then you can follow steps below

If you’re using Symfony Flex:

composer require encore
npm install

 

If you have Symfony < 3.4 and not using Symfony Flex:

npm init
npm install
npm install @symfony/webpack-encore --save-dev
mkdir assets

Webpack Config

Create webpack.config.js file in project root and add configuration below. Don’t forget to mention proper path to your web root and create build directory with write access.

var Encore = require('@symfony/webpack-encore');
 
Encore
    .setOutputPath('public/build/')
    .setPublicPath('/build')
    .cleanupOutputBeforeBuild()
    .enableSourceMaps(!Encore.isProduction())
;
 
module.exports = Encore.getWebpackConfig();

Enabling ReactJS

Let’s add ReactJs and Babel packages and enable preset in Encore. Babel is JavaScript compiler, so it will add some syntaxt sugar to your project.

Install Npm packages:

npm install --save-dev react react-dom prop-types babel-preset-react

Add this line in webpack.config.js. It will enable Babel Preset.

Encore
    // ...
    .enableReactPreset()
;

Configuring Symfony

Now we have to add route and controller, so our web application could serve assets from that route.

In Symfony 4 you can just generate controller

php bin/console make:controller

It will generate controller like below, just insert your twig template path. Usually it’s located in templates folder.

<?php
 
namespace App\Controller;
 
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
 
class AppBundleController extends Controller
{
    /**
     * @Route("/", name="app")
     */
    public function index()
    {
        // replace this line with your own code!
        return $this->render('base.html.twig');
    }
}

Let’s review base.html.twig content. It should contain two blocks with css/js and element with root id. ReactJS will be rendered inside that element.

<div id="root"></div>
{% block stylesheets %}
   <link rel="stylesheet" href="{{ asset('build/app.css') }}">      
{% endblock %}
{% block javascripts %}
  <script src="{{ asset('build/app.js') }}"></script>
{% endblock %}

Adding ReactJS

Let’s add simple ReactJs component. We can name it HelloWorld.

//assets/HelloWorld.jsx
import React, { Component } from 'react';
 
class HelloWorld extends React.Component {
    render() {
        const phrase = 'Hello world';
 
        return (
            <h1>{phrase}</h1>
        );
    }
}
 
export default HelloWorld;

And we should add our entry point index.jsx

//assets/index.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import HelloWorld from "./HelloWorld";
 
ReactDOM.render((
    <HelloWorld />
), document.getElementById('root'));

Finally add it to webpack.config.js

Encore
//...
.addEntry('app', './assets/index.jsx')

Getting Results

So now we should build and compile our application. It can be done by following command:

./node_modules/.bin/encore dev

If you want to get minimified version, run:

./node_modules/.bin/encore production

As final result ReactJS should display ‘Hello World” header.

Conclusion

ReactJS is much more powerful thing and should be used for complex application. Encore and Webpack allow us to manage assets and keep things separated from backend. It’s really useful when you’re building Rich SPA and architecture of you frontend app is pretty complex.

I hope this guide helped you to integrate Symfony Application with ReactJS.


About the Author / Artem Zhuravlev

Artem Zhuravlev. Web developer. Blog writer.

Need help with your website ? Contact with me by email infzanoza@gmail.com for services of experienced web developer.

Follow @infernosquad
2 COMMENTS
olidev

Great tutorial. I have also written this guide on integrating react in symfony using webpack encore. It was good experience working on react through the webpack. This component in symfony is a really good way to integrate react easily.

LEAVE A COMMENT