How to integrate react Router with contao cms

267 Views Asked by At

I would like to integrate react router on an application which has been built on top of Contao CMS 3.5.31. We started rendering react components one at a time on various pages/templates but we will soon need to handle navigation between pages. The main problem that I have is that there is no communication between contao's routing system and react's.

I don't know much about contao and the reading I did on the website's docs seems of little use. In summary, if a page request is made to the server and is not found but exists in react router, I would like to make it so that the application redirects to that page.

Any idea how that might be possible ?

2

There are 2 best solutions below

0
Sirkow On BEST ANSWER

Using hash-based routing like (e.g. /users#list) could solve the problem as long as the part before the hash has been setup by creating a page in contao matching that url (/users in this case). Everything after the hash can be handled by React Router. Refer to this documentation for more information about Hash Routing.

1
fritzmg On

If you don't want to use hash-based routing: the primary question isn't really how to do this in Contao - but how to do this in Symfony. You could use a tutorial like this to get the basics going. However, one thing that you might need to do different is prefixing your route with something, so that you can still serve regular Contao pages (if you need to). So instead of

/**
 * @Route("/{reactRouting}", name="index", defaults={"reactRouting": null})
 */

you would need an arbitrary prefix like

/**
 * @Route("/react/{reactRouting}", name="index", defaults={"reactRouting": null})
 */

and then also configure your BrowserRouter accordingly.

Furthermore, in Contao 4.13+ you can use so called Page Controllers. These work just like regular Symfony controllers, but you can add those pages to your regular Contao site structure and thus you would also be able to define the prefix conveniently via the Contao back end (although you can also hard code the route, see the different path examples).