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

Troubleshooting Next.js app creation in Windows WSL

After setting up WSL 2 on my Windows system for app development, I attempted to create a next.js app using 'npx create-next-app@latest' in the directory '/home/lucastso/dev'. Surprisingly, my terminal displayed the following prompts: â ...

HTML: Base64 image not displaying properly due to incorrect height specification

I have a straightforward base64 image that I am having trouble with. The issue is that only the upper half of the image is displaying. If I try to adjust the height using the "style" attribute in the img tag: style="height: 300px;" it shows correctly. Ho ...

iOS CORS ajax request is stuck at state 0 during processing

I am facing an issue with making a CORS login AJAX call from my iPhone using $.ajax. The request fails and reaches the fail callback, showing the jqXHR object state as: { readyState: 0, status: 0, statusText: "error" } Strangely, on my PC the request ...

Assign a value to an element based on a specific attribute value

I'm working with the following element <input type="text" size="4" name="nightly" value="-1"> My goal is to update the value to 15.9 specifically when name="nightly" Here's what I've attempted so far: document.getElementsByName(&ap ...

When Select2 doesn't find a suitable option, the text "other" will be displayed

Is it possible to show a default option in select2 dropdown if the user's typed input does not match any available options? $("something").select2({ formatNoMatches: function(term) { //return a predefined search choice } }); I have searched ...

When I close all of my tabs or the browser, I aim to clear the local storage

Could you recommend any strategies for clearing local storage upon closing the last tab or browser? I have attempted to use local storage and session storage to keep track of open and closed sessions in an array stored in local storage. However, this meth ...

Javascript code not running as expected

Check out this code snippet: function generateRandomTeams() { const prom = new Promise(() => { // ... console.log('teams', props.state.teams) // logs }) .then(() => { console.log('here') // doesn't log }) ...

Encountering a code ELIFECYCLE error when running npm run dev

In my current project, I am utilizing the nextjs framework along with various npm package modules. Initially, everything was working smoothly during development. However, upon restarting the application using the command npm run dev, I encountered an error ...

Trouble with Bootstrap popover functionality

Twitter bootstrap-2.3.2 popover is being utilized in my BackboneJs project. When I click, a function is triggered to open the popover: <li> <a class="candidPopover" href="#" id="loginUser" rel="popover"><%= candidateName %></a> & ...

Convert the property that starts with XX from XML to JSON

I am currently working on a function that looks like this request.execute('[someSP].[spSomeSP]', function(err, dataset) { _.map(dataset, function(items) { console.log(items); }); }); When the _.map(...) is executed, it retu ...

Arrange a JavaScript map based on its values and ensure that a specific field index remains at the top position

I'm sure this question may seem simple to some, but as a JavaScript novice, I couldn't find the answer myself. Here is the code snippet I'm working with: Let map = new Map<String,String> map.set('0', select) map.set('1&a ...

wrap <td> data in a link with vue depending on certain conditions

I'm trying to customize the display of a particular table cell td. I want to show the data in a link if a certain condition is met, and if not, just show the data as text. However, I'm encountering some difficulties in implementing this. I have ...

How come the HTML page served by the express.js route isn't linked to a CSS stylesheet?

Recently, I've been working with a server.js file that imports a router const path = require("path"); const express = require("express"); const app = express(); const PORT = 8080; app.use(express.urlencoded({ extended: true })); app.use(express.jso ...

Convert the JSON data received from a jQuery AJAX call into a visually appealing HTML table

Utilizing AJAX as the action, I have created a search form. In the success of the AJAX request, I am seeking a way to update a specific div without refreshing the entire page. Below is my form: <?php $properties = array('id' => &ap ...

TypeError was not handled: Attempted to use the 'in' operator to search for 'electron' in an undefined variable at next-dev.js line 8

I encountered an unexpected error while attempting to run next.js in development mode. The strange part is that I'm not utilizing electron in this application at all. An uncaught TypeError occurred: Cannot use 'in' operator to search for &a ...

Best method for connecting user input with a class

I'm currently working with a WYSIWYG editor (Tinymce) that allows users to post YouTube videos. In order to make the video content responsive, I need to add the class "video-container" around any "iframe" tags inserted when users paste a YouTube link ...

Carousel-Owl, glide through two items simultaneously

I am currently in the process of developing a slider using the beta version of Owl-Carousel 2, but I am encountering several issues. My goal is to configure the owlCarousel to function as follows: It should scroll through 2 items at a time while displayin ...

What is the method to obtain the zoom level in IE5 using JavaScript/jQuery?

Currently, I am using IE11 and have enabled emulation in the developer tools to change the document mode to 5. My goal now is to determine the current zoom level, which I adjust in the settings of IE. https://i.stack.imgur.com/DYftF.png The code snippet ...

Code functions properly on local host but encounters errors when deployed to live server

My comment system was working fine on localhost using PHP, AJAX and JavaScript. However, after transferring my website to a live server, the code does not seem to be functioning properly. Here is an example of the script: <script type="text/javascript ...

How to effectively utilize JSON responses with jQuery Mobile?

I've been facing an issue with working on my JSON result in JavaScript. Can anyone provide some insight? Even though the JSON call returns a success status code (200) and I can view the data in Firebug, no alert is being displayed. $(document).on(& ...