I use React to a page in symfony with vite:
This is the base:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{% block title %}Welcome!{% endblock %}</title>
{# Run `composer require symfony/webpack-encore-bundle`
and uncomment the following Encore helpers to start using Symfony UX #}
<link rel="shortcut icon" type="image/x-icon" href="{{ asset('images/Logo 2.png') }}">
<meta
name="viewport" content="width=device-width, initial-scale=1">
{% block stylesheets %}
{{ vite_entry_link_tags('app') }}
{% endblock %}
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,300;0,400;0,500;0,600;0,700;1,300;1,400;1,500;1,600;1,700&display=swap" rel="stylesheet">
</head>
<body>
{% block body %}{% endblock %}
{% block javascripts %}
{{ vite_entry_script_tags('app') }}
{% endblock %}
</body>
</html>
This is the twig:
{% extends 'base.html.twig' %}
{% block title %}Reseau Sociaux{% endblock %}
{% block body %}
<div id="app"></div>
{% endblock %}
This is the controller:
/**
* @Route("/reseau-sociaux", name="reseau-sociaux_home")
* @IsGranted("ROLE_USER")
*/
public function reseauSociaux(Request $request)
{
return $this->render('reseauSociaux/reseauSociaux.html.twig');
}
And this is my react:
import React from "react";
import { createRoot } from 'react-dom/client';
import Actualite from './pageActualite/Actualite'
import './styles/app.css';
import { BrowserRouter, Routes, Route } from "react-router-dom";
import ProfilUser from "./otherPages/ProfilUser/ProfilUser";
const App = () => {
return (
<BrowserRouter>
<Routes>
<Route path="reseau-sociaux" element={<Actualite />}/>
<Route path="/reseau-sociaux/profil" element={<ProfilUser />}/>
</Routes>
</BrowserRouter>
);
}
const rootElement = document.querySelector('#app');
const root = createRoot(rootElement);
root.render(<App />);
The problem is the route, react-router-dom is working well but if I refresh the page the error is: no route found, an error from symfony. For example if I refresh the /reseau-sociaux/profil page, I get the error because there is no route /reseau-sociaux/profil in my symfony.
I have others twig pages too but they work well
Sure... it is the symfony route that not match if you extend the route from /reseau-sociaux
to /reseau-sociaux/profil
. You must symfony tell that your route can have sub pathes.
You can change the route parameters to match on sub pathes like
/**
* @Route("/reseau-sociaux/{sub}", name="reseau-sociaux_home", requirements={"sub"=".+"})
* @IsGranted("ROLE_USER")
*/
public function reseauSociaux(Request $request, ?string $sub = null)
{
return $this->render('reseauSociaux/reseauSociaux.html.twig');
}