5

I am using React JS in my theme (installed via NPM), and exporting views using REST. I want to render the JSON view data into React components and call them in the twig templates.

The way I have it working now is I have js/main.js importing components eg: js/components/slider.jsx etc. The component files decide where to render. Eg:


ReactDOM.render(
  document.getElementById('elementid')
);

I have a gulp task running which bundles, transforms ES6 - ES5, and uglifies all the JS imported in js/main.js into js/script.js which is the only JS loading from the theme. I'm not sure if this is the best option for performance.

Maybe another option is to compile each component (ES6 must be transformed to ES5) into it's own JS file and define them as libraries, which can be then called in the twig templates?

I have tried to use TwigReactDirective but I get errors following the instructions.

Are there better options / ways of doing this?

2
  • This is a really good question even if it is not Drupal centric as it deals with different ways of rendering data from Drupal via Twig. Starring it.
    – Kevin
    Commented Apr 19, 2017 at 0:47
  • Yes it has had me thinking, researching and experimenting for days. I'm still exploring the options. I found another interesting presentation video from Drupalcon of how it can be handled: events.drupal.org/dublin2016/sessions/… Commented Apr 19, 2017 at 10:46

1 Answer 1

2

After doing some research, I found 3 options to render React components on the server side.

  • Use the PHP V8Js extension to run an embedded V8 engine
  • Execute node.js processes on demand
  • Run a node.js rendering daemon for rendering

Rendering on the server side is beneficial for performance of the initial page load. Using the V8Js extension and a twig extension like Tesonet seems like the best option for me.

V8Js installation instructions can be found here

Some other good options to try out are: React Renderer or symfony-react-sandbox or React Bundle. Symfony React Sandbox integrates React Bundle. React Bundle integrates React Renderer.

Read more here

2
  • It would be interesting to hear which you ended up going with, and how your experiences were.
    – Magick
    Commented Aug 30, 2017 at 14:02
  • 1
    I had difficulties getting the V8JS extension to work, it was not as simple as just enabling it in the php.ini file unfortunately. That particular project I haven't worked on since, but I did work on a new similar project afterwards and made the isomorphic application outside the Drupal directory which runs on a node JS server, which does not use twig templating, but EJS instead. I will go back to the original project soon and have another go at installing V8JS. Commented Aug 31, 2017 at 9:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.