Managing JavaScript files in Symfony-based applications 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 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 that 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 of 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.
Start Growing with Cloudways PHP Hosting Today
People Love us because we never compromise on hosting
Prerequisites
A basic knowledge of React and Object-oriented programming with PHP will help you get the best out of this article. 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. Alternatively, set up a Cloudways account to launch a server and follow this tutorial to set up a Symfony 4 project in just a few minutes.
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. On production, you should use a web server like Nginx or Apache, Cloudways’ best PHP hosting supports both. For now, open up your terminal and use the command mentioned below to change the 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, and you should see this:
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 enabling 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 to 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() { return $this->render('default/index.html.twig'); } }
You might also like: Symfony 4: Routes, Controllers & Templates
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 the 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, including a div with an id of root. You will use it as a 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. The 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 that 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
You might also like: Create and Run PHP Unit Testing
Summary
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 having a diligent look.
This article serves 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 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.
Owais Khan
Owais works as a Marketing Manager at Cloudways (managed hosting platform) where he focuses on growth, demand generation, and strategic partnerships. With more than a decade of experience in digital marketing and B2B, Owais prefers to build systems that help teams achieve their full potential.