Codementor Events

Getting started With React in Symfony Using Webpack Encore

Published Sep 18, 2018Last updated Mar 16, 2019
Getting started With React in Symfony Using Webpack Encore

Reading Time: 6 minutes

Managing JavaScript files in Symfony-based application is easy, thanks to the the introduction of a pure-JavaScript library called Symfony Webpack Encore. It offers a simplified process for working with CSS and JavaScript files in Symfony. In my previous article on Getting Started with Vue.js in Symfony, I pointed out that Symfony as a PHP framework remains neutral when it comes to making a choice to implement the client logic and greater functionalities in web applications.

Keeping that in view, this post will demonstrate a step-by-step process for setting up a Symfony React application. React.js is an open-source JavaScript library which is used for building user interfaces specifically for single page applications. Irrespective of how you prefer to use React in your application, either to build a single page app or to power a specific part of your frontend, by the time you have read this article in full, you will have had a good foundational knowledge on how to start a new project with React or introduce it into an existing Symfony encore application.

In this blog, you will learn to build a simple Symfony reactjs app that uses a backend API. Instead of setting up the backend service in this application, I’ll make use of a fake online REST API (JSONPlaceholder) for testing and prototyping purposes.

Prerequisites

A basic knowledge of React and Object oriented programming with PHP will help you get the best out of this article. Do ensure that you have Node.js and Yarn package manager installed on your system.

Setting Up a New Symfony Application

To kick-start, use composer to quickly set up a new Symfony project.

Open up the terminal and run the command mentioned below to create a new project named symfony-react-starter and install all the dependencies for a standard Symfony application:

composer create-project symfony/website-skeleton symfony-react-starter

Start the Application

By default, the application comes installed with a Symfony PHP web server for the development process. For now, open up your terminal and use the command mentioned below to change directory into the newly created project folder and start the development server:

// change directory 
cd symfony-react-starter 

// start the server
php bin/console server:run

The command mentioned above will create the development folder on http://localhost:8000. Open up that link in your favorite browser, you should see this:

symfony welcome page

Now having the application running, the next step is to configure Webpack Encore and initiate the setup of React.js for your application.

Configure Symfony Encore, Install React and Other Dependencies

As pointed out above, I will use Webpack Encore in this tutorial to set up React for the application. Therefore, you must run the command mentioned below to install Webpack Encore, React and other dependencies:

# Create package.json, webpack.config.js and add node\_modules to .gitignore composer require symfony/webpack-encore-pack 

# Add react dependencies 
yarn add --dev react react-dom prop-types babel-preset-react yarn install

Once you are done with the configuration process, move on to the enabling of React in your application and also set up an entry point for Webpack Encore by navigating to ./webpack.config.js. Edit the file as shown below:

// webpack.config.js
// ...

Encore
  // ...
  .enableReactPreset()
  // uncomment to define the assets of the project
  .addEntry('js/app', './assets/js/app.js');
    

Finally, to complete this process, create a subdirectory named js within the assets folder and then add an app.js file into it.

Create The Route And Controller

In the terminal, run the command mentioned below to create a controller named DefaultController:

php bin/console make:controller Default

Open the newly created controller and edit as shown below:

// ./src/Controller/DefaultController.php

<?php

namespace App\Controller;

use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller

{

    /**
    * @Route("/", name="default")
    */

    public function indexAction()
    {
    &nbsp;return $this->render('default/index.html.twig');

    }

}

Create the AppComponent

It’s time to create the AppComponent. For this, you must open the app.js and paste the content mentioned below, in it:

import React from 'react';
import ReactDOM from 'react-dom';
import Items from './Components/Items';

class App extends React.Component {
    constructor() {
      super();
        this.state = {
        entries: []
      };
  }

    componentDidMount() {
        fetch('https://jsonplaceholder.typicode.com/posts/')
        .then(response => response.json())
        .then(entries => {
        this.setState({
        entries
        });
        });
    }
    render() {
      return (
        <div className="row">
            {this.state.entries.map(
                ({ id, title, body }) => (
                      <Items
                      key={id}
                      title={title}
                      body={body}
                      >
                      </Items\>
                )
            )}
        </div>
      );
    }
}
ReactDOM.render(<App />, document.getElementById('root'));

Here, you are basically importing React into the application and also importing an Item component which you will create at a later stage. Within the ComponentDidMount() life cycle method, you have to make an API call to https://jsonplaceholder.typicode.com/posts/, it will fetch the dummy post to test out application.

Creating the Items Component

The Items component basically receives props from the main component and renders the contents to the view. To set it up, create a new subfolder named Components within ./assets/js. Now, create a new file called Items.js inside the newly created folder. Open up this file and edit:

// ./assets/js/components/Items.js

import React from 'react';

const Items = ({ id, title, body }) => (
    <div key={id} className="card col-md-4" style={{width:200}}>
        <div className="card-body">
        <p>{id}</p>
        <h4 className="card-title">{title}</h4>
        <p className="card-text">{body}</p>
        <a href="https://jsonplaceholder.typicode.com/posts/" className="btn btn-primary">More Details</a\>
        </div>
    </div>
);
export default Items;

Bootstrap card is used here, to give each post a default layout and styling.

Display React Component Content

Navigate back to the default template generated for our application, include a div with an id of root. You will use it as React mount point. Edit the content of default/index.html.twig as shown below:

./templates/default/index.html.twig

{% extends 'base.html.twig' %}

{% block title %} Symfony React Starter {% endblock %}

{% block body %}

<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="#"> Symfony React Starter </a>
</nav>
<div id="root"></div>

{% endblock %}

Base Template

Edit the application’s base template and include the compiled JavaScript file in it. Compilation command will execute in the next step.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{% block title %}Welcome!{% endblock %}</title>

    {% block stylesheets %}{% endblock %}
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"\>
    </head>
    <body>
    {% block body %}{% endblock %}
    {% block javascripts %}
    
<!-- Include the compiled script--\>
<script type="text/javascript" src="{{ asset('build/js/app.js') }}"></script>
{% endblock %}
</body>
</html>

Test the Symfony Application and See it Working

Now you can compile the asset which the Symfony template will use. See the changes by using the following command:

yarn run encore dev --watch

Also, ensure that your development server is currently running. If otherwise, open another terminal and navigate to the root directory of your project, then run the following command:

php bin/console server:run

symfony react starter

Wrapping Up

Developing and successfully running an awesome application requires a lot of effort, time and tools. When it comes to working with Symfony Framework, a frontend library matters the most. Symfony gives you the opportunity to integrate great JavaScript libraries like React easily into your application, making your app’s front end really worthy and have a diligent look.

This article serves you as a quick guide on how to develop a fully functional Symfony React application using Webpack Encore. It’s a great JavaScript package that allows you to easily set up creative front-end applications in Symfony.

I hope you that you will find this Symfony Webpack Encore tutorial really useful. You can share your thoughts in the comment section below and feel free to check out the complete source code here on GitHub.

Discover and read more posts from Oluyemi Olususi
get started
post commentsBe the first to share your opinion
Show more replies