Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting react component into handlebars in client side

How to inject react component into handlebar template which is loading dynamically at run time.

like image 448
Partha Sarathi Nanda Avatar asked Aug 14 '17 05:08

Partha Sarathi Nanda


1 Answers

edit: tl;dr: This is a great question. Injecting pre-rendered React components into an html templating language (like handlebars) can improve the load times of your site and improve the "indexability" of your content for search engines (your SEO). the trick is you have to server-side render (SSR) and you don't want to load all of the code into the browser on the initial request so you need code-splitting. These can be accomplished with webpack. Until recently they have not been possible without a framework like Next.js... There are now 3 options, and the conclusion I have come to is that the only one worth using is: React-Universal-Component

If you want to learn more about the benefits you get from rendering your content into HTML before the JS assets, CSS assts, etc. are loaded, this article on Isomorphic or Universal Javascript is a good place to start. Writing Isomorphic/Universal JavaScript is about writing code that is flexible in its ability to render client-side or server-side.

There are a couple if React top-level APIs that make this easy, and a handful of transpiling/compiling/bundling libraries (I use Webpack), that are necessary (if you don't want to compile the template in the browser).

Because React components are almost always written in JSX they must be transpiled to JavaScript before they can be rendered. This is typically done with ReactDOM.render() which will call React.createElement() for us.

React also has a function, ReactDOMServer.renderToString() which takes the React element, builds the HTML (on the server-side) and converts it into a string. This is what enables us to inject pre-rendered React into html templates.

For an example of the process which I have just described, see this example, but it's out of date now.

Conclusion: Injecting a React component into a handlebar template is not worth its time because there are finally libraries to help us do this (see my first link). IMO SSR React is important for sites that need the SEO benefits, and it will also improve your load times (especially on under-powered devices) if your app properly performs SSR and code-splitting.

like image 200
Drew2 Avatar answered Oct 20 '22 05:10

Drew2