I would like to develop themes/plugins for WordPress
based on React
. To make it search engine friendly, I need it to be rendered initially on the server (serverside-rendering).
The only way to do this, as far as I know, is to use react-php-v8js, which requires the PECL V8js extension. This is a problem since I have no control over the platform on which these themes/plugins will be run.
Is there a way to make React
and WordPress
work together without having to install additional extensions? Perhaps by building/compiling React
files into PHP
?
There’s an article that describes how to do this:
https://sebastiandedeyne.com/server-side-rendering-javascript-from-php/
But it’s a fairly complex setup and it requires using composer. That can be difficult in WordPress projects since WordPress tends to completely eschew the modern php architecture.
If you’re looking for a library to help with SSR in PHP:
https://github.com/spatie/server-side-rendering
Best of luck on it.
If you want your content to be indexed by search engine without js, you can print your minimal content using WordPress, just the bare minimum + crucial meta tags, maybe localize some initial state for your react app to boot. A bare bone theme such http://underscores.me/ would be sufficient. When js is available, you can replace your whole WordPress generated content with React ones.
The ideal one is to have React generate the content for you. But it’s hard until we can see that nodejs / PECL V8js extension available everywhere.
If you can at least install nodejs and launch a node process then it should be ok, although not so simple.
You would need to generate a ssr version of your assets and use it in a node process that would listen on a socket to write the html result..
In your controller you can create a socket to your node process (something like stream_socket_client(…)) and then you can send a dummy function written as a javascript string to that socket (something like stream_socket_sendto($sock, “getResultForMyWidget(someParams){…}”)). That function would be evaluated in the node process that would return the response to the controller (the html response as a ReactDOMServer.renderToString from the component you want to render).
That’s it for the big picture.
There is a symfony plugin that illustates it very clearly (see this github) and comes with a dummy server node process to illustrate how it handles the socket listening and eval of the incoming function and returns the html result. See also the example in the sandbox for a bigger picture and in depth implementation. You should be able to adapt it to wordpress.