Drupal X React Server Side rendering with hydrateRoot
Todays article is covering how to do SSR from php without JS, hydrate it in frontend with React.
So when you talk about SSR with react in an complete javascript environment its pretty simple, there is no complications involved in it.
But when it comes to drupal as your backend, complications starts -
"You cannot execute your javascript in backend. 😊"
So how to do it ?
Well lets just dive into the tutorial now. First rule of hydateRoot your server rendered DOM element should be exactly and I mean "exactly" same as your client rendered DOM element, you can use diff checker to validate that.
For todays example we will try to hydrate an paragraph from drupal.
So you have to copy the element from Client side rendering using browser dev tools which you are trying to hydrate and paste it as it is in your twig file, you should not format that element at all, because then your hydrating algorithm will throw error of element mismatch.
Now once this is done go ahead and write hydrate root logic in javascript.
So to test it out I have made an setTimeout function which will change an react state storing the heading of our section.
Well hydration does works this way, but this whole process requires no human error and then only you could have drupal SSR hydrated by react.
Maybe their are other ways to be explored so please let me know in the comments if I am missing something any suggestions.
Thanks for reading this article. Have a nice day.