Server-Side Rendering In ASP.NET

5 (100%) 1 vote

BestASPNETHostingReview.com | Best and cheap ASP.NET MVC hosting. Server-side rendering allows you to pre-render the initial state of your React components server-side. This speeds up initial page loads as users do not need to wait for all the JavaScript to load before seeing the web page.

asp.net

To use server-side rendering in your application, follow the following steps:

1 – Modify App_Start\ReactConfig.cs (for ASP.NET MVC 4 or 5) or Startup.cs (for ASP.NET Core) to reference your components:

This tells ReactJS.NET to load all the relevant JavaScript files server-side. The JavaScript files of all the components you want to load and all their dependencies should be included here.

2 – In your ASP.NET MVC view, call Html.React to render a component server-side, passing it the name of the component, and any required props.

3 – Call Html.ReactInitJavaScript at the bottom of the page (just above the </body>) to render initialisation scripts. Note that this does not load the JavaScript files for your components, it only renders the initialisation code.

4 – Hit the page and admire the server-rendered beauty:

The server-rendered HTML will automatically be reused by React client-side, meaning your initial render will be super fast.

If you encounter any errors with the JavaScript, you may want to temporarily disable server-side rendering in order to debug your components in your browser. You can do this by calling DisableServerSideRendering() in your ReactJS.NET config.

For a more in-depth example, take a look at the included sample application (React.Samples.Mvc4).

5 – Server-side only rendering

If there is no need to have a React application client side and you just want to use the server side rendering but without the React specific data attributes, call Html.React and pass serverOnly parameter as true.

And the HTML will look like the one following which is a lot cleaner. In this case there is no need to load the React script or call the Html.ReactInitJavaScript() meth