Can anybody help me set up React in my Grav site?

I’ve tried using Vite to install React in a directory in my Grav theme, but it’s not recognized or compiled by the built in Grav (PHP) web server. How do I add React to my Grav site so that my twig template files will recognize and run React and .jsx? Any help is appreciated.

@skipper, The question is quite broad and the provided information is a bit minimal.

It would be handy for us to understand what research you’ve done, what you’ve tried, what you expect would happen and where you got stuck… Knowing what skills level you have in building a React frontend in combination with a PHP server in general might also help.

Please have a look at The art of asking great questions. There are a couple of topics that might help improving your question.

Hi. I’m attempting to follow the tutorial on the React docs here:

https://react.dev/learn/add-react-to-an-existing-project

I’ve tried both suggestions, setting up a modular javascript environment and also via Vite. I need my project (or more specifically my theme) to pull in React and be able to execute javascript (.jsx) files. I can get React in my theme (node_modules in the theme folder via npm) but I get errors when I try to run the following code:

import { createRoot } from ‘react-dom/client’;
etc. from index.js in the docs

Uncaught TypeError: The specifier “react-dom/client” was a bare specifier, but was not remapped to anything. Relative module specifiers must start with “./”, “…/” or “/”.

@skipper, Again, you are not providing much info… Did you read the document I referred to?

In general, apart from loading some js files, generated by the npm build process, into the generated page using the Asset Manager in Twig or PHP, there is not much more for Grav to do.

It seems to be a React and js knowledge issue, for which plenty tutorials and help forums are available on the web.

1 Like

I can answer my own question. I was able to get a React app working inside Grav. It really had very little to do with Grav. The basic steps for me were:

  1. Use webpack and babel to build my React app (.jsx) to native javascript in a bundle.js file.
  2. Import the bundle.js file using the Grav asset manager.

That’s sufficient to get a basic React app working. I did a couple other things:

I used the example from example with json files to convert Grav data (a list of child posts) to json, and then brought in the json with fetch(). Then you can do whatever with the data. In my case, I replaced the Tagcloud, SimpleSearch, and Pagination plugins with my own versions in React.

Very interesting. I am curious, if your React app works by itself, what is the purpose of using also Grav?