How to Add React js to Symfony 6 Part 1
In this tutorial, we are going to see how to add React js to Symfony 6 with Encore, I assume that you have already installed a fresh new Symfony 6 application.
Install Encore
First, let's install Encore and the packages that we are going to need.
Run the commands below:
//first
composer require symfony/webpack-encore-bundle
//second
yarn install
//third
yarn add react react-dom prop-types
yarn add @babel/preset-react@^7.0.0 --dev
Enable React js
Next step, we need to enable React js, so let's update the file webpack.config.js and add this line .enableReactPreset()
// webpack.config.js
Encore
// ...
.addEntry('main', './assets/main.js')
+ .enableReactPreset()()
;
Create the home component
Inside the asset folder let's create a new folder 'components' inside this folder add a new file 'Home.js' inside add the code below.
import React from 'react';
const Home = () => {
return(
<div className="container">
<h1>Add React js to Symfony 6</h1>
</div>
)
}
export default Home;
Update the file app.js
Next, update the file app.js, let's import the home component and add it to the app.
import React from 'react';
import ReactDOM from 'react-dom/client';
import Home from './components/Home';
ReactDOM.createRoot(document.getElementById('app')).render(
<Home />
);