Is there a more efficient method for implementing server side rendering in a Next.js application?

Currently, I am implementing server-side rendering in my Next.js application. This specific component is responsible for returning HTML content. I'm wondering if there are more efficient methods available?

import Feature from 'components/home/Feature/Feature';
import HeroArea from 'components/home/HeroArea/HeroArea';
import HeroFeatures from 'components/home/HeroFeatures/HeroFeatures';
import Newsletter from 'components/home/Newsletter/Newsletter';
import PopularCryptocurrencies from 'components/home/PopularCryptocurrencies/PopularCryptocurrencies';
import Testimonial from 'components/home/Testimonial/Testimonial';
import SponsorCard from 'components/sponsor_card/SponserCard';
import type { NextPage } from 'next';
import { renderToString } from 'react-dom/server';

import { getTranslations } from '../utils/translations';
interface IndexType {
  popularCryptoData: {
    current_price: number;
    high_24h: number;
    id: string;
    low_24h: number;
    market_cap: number;
    market_cap_rank: 1;
    name: string;
    price_change_24h: number;
    symbol: string;
    total_volume: number;
    image: string;
  }[];
}

const Home: NextPage<any> = ({ heroFeatures, feature, testimonial, t }) => {
  return (
    <div data-theme='dark'>
      <main className='relative overflow-hidden'>
        <div className="bg-[url('../public/images/DarkBlueBG.svg')] bg-cover    ">
          <HeroArea />
          <div dangerouslySetInnerHTML={{ __html: heroFeatures }} />

          <PopularCryptocurrencies />

          <div dangerouslySetInnerHTML={{ __html: feature }} />
          <div dangerouslySetInnerHTML={{ __html: testimonial }} />
          <Newsletter />
          <div className='block absolute'>
            <SponsorCard />
          </div>
        </div>
      </main>
    </div>
  );
};
export const getServerSideProps = async ({ locale }: any) => {
  const t = getTranslations(locale);

  const heroFeatures = renderToString(<HeroFeatures t={t} />);
  const feature = renderToString(<Feature t={t} />);
  const testimonial = renderToString(<Testimonial t={t} />);

  return {
    props: {
      heroFeatures,
      feature,
      testimonial,
      t,
    },
  };
};

export default Home;

This represents my Home page where I utilize the react/dom-server.renderToString method along with dangerouslySetInnerHTML and _html.

The current implementation effectively handles server-side rendering. Nonetheless, I am open to exploring any superior alternatives.

Answer №1

Exercise caution with the use of dangerouslySetInnerHTML
, as it can be risky and best to find alternative solutions.

Avoid passing formatted HTML code or components as props whenever possible.

Consider only returning t from getServerSideProps and rendering components in Home. Ensure that Next.js is set up to render the components server-side.

For example, instead of:

<div dangerouslySetInnerHTML={{ __html: heroFeatures }} />

try:

<div><HeroFeatures t={t} /><div>

(You may also be able to exclude the extra <div>.)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having difficulty coming back from a promise catch block

I'm struggling to populate a menu list from my PouchDB database because I am unable to retrieve anything within the promise that is executed after calling get on the db. Below is the code in question: <MenuList> {this.populateSavedClues()} ...

In NextJS, the fetch method will result in a 404 error, but using await with the post

When working with NextJS, I noticed that the following POST call is successful using await post: const payload = { 'param1': param1, 'param2': param2 }; const response = await post<any,any>("/app/action", payload) ...

JavaScript: Automatically retrieving the if else function

I need help automating the calculation of the number of days a person worked based on their "in-time" and "out-time". I've tried to implement this in my JS code, but it's not working as expected. HTML <fieldset> In-Time: <input clas ...

Convert the class to a file upload using jQuery

I am currently working on a project involving a file upload script. I have multiple directories where the files need to be uploaded, and I'm attempting to use a single form for this purpose. So far, I have been able to change the form class using jQu ...

How can we control the content being displayed on our tree?

Is there a way to customize the view of our V-treeview by filtering what is displayed? By entering the beginning of an element key in the filter field input, the tree will only show elements whose keys match the input. I am working on Vue.js with the late ...

Violation of Invariant: Incorrect hook usage or a cross-origin issue has occurred

After successfully getting my function to work, I decided to implement a loop for feedback from the backend post SSR. Wanting to utilize hooks, I converted it into a functional component and began writing code. However, even with an empty hook, I encounter ...

Leverage the variables' values to access property

There is a way to use this possibility: let eventSelected = "333"; let bestResult = result.personal_records[eventSelected]?.single?.best //like searching like this: result.personal_records.333?.single?.best However, when deali ...

Creating a collapsing drop down menu with CSS

I utilized a code snippet that I found on the following website: Modifications were made to the code as shown below: <div class="col-md-12"> ... </div> However, after rearranging the form tag, the drop-down menu collapse ...

The collection is not an array

I am currently running the following code: var n = []; jQuery.toJSON( n ); Interestingly, on one page I receive "[]", while on another I get ""[]"". Both pages are utilizing the same version of jQuery along with a toJson Plugin. Upon inspecting the arra ...

Rendering elements dynamically using ng-repeat following an AJAX request

Feeling frustrated, I made an $http request ApiService.get_request_params("api/endpoint").then( function(data) { $scope.customers = data }, function(err) { } ); The $scope.customers should be bound to an ng-repeat. I can see the ...

Handling errors within classes in JavaScript/TypeScript

Imagine having an interface structured as follows: class Something { constructor(things) { if (things) { doSomething(); } else return { errorCode: 1 } } } Does this code appear to be correct? When using TypeScript, I en ...

Ways to achieve combined outcomes using ng-repeat

Check out this plunker. <div ng-repeat="subCategory in subCategorys | filter:{tags:tag}:true | orderBy:'id'"> {{subCategory.id}} {{subCategory.name}} {{subCategory.tags}} <br/><br/> The detailed information of ...

How can you disable an 'option' HTML5 element using the AngularJS methodology?

How can I disable an 'option' element in HTML5 using AngularJS? Currently, I am working with AngularJS v1.2.25. Here is the Plunk Link for reference: https://plnkr.co/edit/fS1uKZ <!-- CODE BEGIN --> <!DOCTYPE html> <html> ...

I'm encountering a Type Error message in VS Code terminal stating that converting data to string is not a function. Can someone please help me understand this type error? I am new to Node.js and

const fileSystem = require('fs'); const data = fileSystem.readFileSync('example.txt'); if (data) console.log(data.toString()); console.log('Program Ended'); This is the code I wrote: and this is the error message my terminal ...

Using an external module in a Vue SFC: a beginner's guide

Recently delving into Vue, I'm working on constructing an app that incorporates Typescript and the vue-property-decorator. Venturing into using external modules within a Single File Component (SFC), my aim is to design a calendar component utilizing t ...

Leveraging the power of JavaScript Math methods to dictate the Co-ordinates of HTML Canvas .fillRect

Greetings to everyone! I have dedicated my entire evening to understanding how to implement the (Math.floor(Math.random()) function as the coordinates for the .fillRect method on an HTML canvas element. Despite searching through this website and various ...

Swapping out the document.createElement() method for React.createElement()

In a JavaScript library, I utilize document.createElement() to create an HTMLElement. Now, I am looking to develop a React library with the same functionality. My initial thought was to substitute document.createElement() with React.createElement(). There ...

The identifier 'name' is not found in the specified data type

How can I resolve the error 'Property 'name' does not exist on type' in TypeScript? Here is the code block : **Environment.prod.ts** export const environment = { production: true, name:"(Production)", apiUrl: 'https://tes ...

Is it possible to display data on a webpage without using dynamic content, or do I need to rely on JavaScript

Imagine a scenario where I have a single-page website and I want to optimize the loading time by only displaying content below the fold when the user clicks on a link to access it. However, I don't want users with disabled JavaScript to miss out on th ...

Express template failing to connect with scripts, css, and images

When using Express, I encounter difficulty in getting the css, js, and images to link up correctly when running the index.html file. The images are not showing up and the css and js files are not linking properly. <link rel="stylesheet" type="text/css" ...