How to Add React js to Symfony 6 Part 2

2 years ago admin Symfony

In the second part of this tutorial, how to add React js to Symfony 6 with Encore, we will display the Home component content on the home page.


Create the HomeController

Let's create a new Symfony Controller we name it HomeController which renders the home page that we will add later.

                                                    
                                                                                                                
<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;

class HomeController extends AbstractController
{
    #[Route('/home', name: 'app_home')]
    public function index()
    {
        return $this->render('index.html.twig');
    }
}


Create the home page

Inside templates, we add a new file 'index.html.twig' here we display the home component.

                                                        
                                                                                                                        
{% extends 'base.html.twig' %}
{% block body %}
    <div id="app"></div>
{% endblock %}

Add routes

Next, inside config/routes.yaml we add the routes.

Now you can run symfony server:start and yarn run encore dev --watch to watch changes.

Photo of a demo

                                                        
                                                                                                                        
home_app:
    path: /
    controller: App\Controller\HomeController::index