Next.js is refusing to render an array of HTML elements

Consider this scenario where I have a block of code in TypeScript that attempts to create and display a list of elements. Here is a sample implementation:

   const MenuList = ():ReactElement => {

    const router = useRouter(),
liElements:any = [];
console.log(navRoutes)

useEffect(() => {
    for(let elem in navRoutes){
        const htmlElement = (
            <>
                <li>
                    <a
                        href={navRoutes[elem].href}
                    >
                        {navRoutes[elem].name}
                    </a>
                </li>
            </>
        )
        liElements.push(htmlElement)
    }
    
    
})
console.log(liElements,'dups')
return (
    <>
        <ul className={''}>
    {liElements.map((elem:any) => elem)}
        </ul>
    </>
)

}

export { MenuList }`

I wonder why the statement "{liElements.map((elem:any) => elem)}" doesn't render any elements?

Answer №1

The issue lies in the incorrect usage of the useEffect hook. However, in this particular scenario, the use of it is unnecessary. You can simply write the code without it:

const MenuList = (): ReactElement => {

    const router = useRouter(), liElements: any = [];

    for (let elem in navRoutes) {
        const htmlElement = (
            <>
                <li>
                    <a
                        href={navRoutes[elem].href}
                    >
                        {navRoutes[elem].name}
                    </a>
                </li>
            </>
        )
        liElements.push(htmlElement)
    }

    return (
        <>
            <ul className={''}>
                {liElements.map((elem: any) => elem)}
            </ul>
        </>
    )
}

If you're curious about when and how to use the useEffect hook:

  • Use it to fetch data from an API (or perform other asynchronous operations) and store the result in state (e.g., using useState). It is important not to modify anything outside the scope of useEffect (as you are currently doing), as it can lead to unpredictable behavior. If you want to save the result of useEffect, use useState.
  • Use it to modify HTML outside of the React component (e.g., setting the meta title). This is useful because you can execute code inside useEffect only once or specify when it should be executed using dependencies as the second argument. Keep in mind that your component function can be called multiple times, even during a single rendering.

By the way, I'm not sure what navRoutes refers to in your code :/

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

Invoke a Google Apps Script through AJAX that necessitates authentication

I am looking to access a Google Apps Script via AJAX that requires user authorization to send an email from their Gmail account. The challenge lies in the fact that I need to send the email from within the Google Apps Script. The call originates from my w ...

Issue: mongoose.model is not a valid function

I've been diving into several MEAN tutorials, and I've hit a snag that none of them seem to address. I keep encountering this error message: Uncaught TypeError: mongoose.model is not a function Even after removing node_modules and reinstalling ...

The application within the Main Module is not being acknowledged by the other components within the module

I am facing an issue with my AngularJS application where the directive I created within the 'FormTest' module is not recognizing the variable 'app' even though it is defined within the same module. The error message I receive is TS2304 ...

Clicking on the overlay does not close the bootstrap collapsed toggle

I'm currently facing an issue where I need to add a listener that closes the menu when clicked away. The code snippet below shows my attempt at solving this problem: $("body").click(function(e){ var $box1 = $('.navbar-toggle'); var $b ...

In Vue, when you want to display text after reaching a height of 50px, any additional text will automatically be replaced by five full

https://i.stack.imgur.com/mp0YJ.png >>>>>>>>>Explore Sandbox Example <div style="height:50px"> ...

Tips for positioning a div within a grid:

Looking for help with displaying news on your CMS page? You may have encountered an issue trying to show the title and content in two columns within a row. Here is some CSS code that might guide you in the right direction: *{ margin:0; padding:0; ...

Scraping an unbalanced HTML document using Beautiful Soup 4

While working with html files, I often come across partial files that have unbalanced html tags. For instance, there might be a missing <title> tag in the first line of this partial html file. Despite this issue, I wonder if Beautiful Soup can still ...

I am looking for a way to convert the date format from "yyyy-MM-dd" to "dd-MM-yyyy" in NestJs

I need help with changing the date format from "yyyy-MM-dd" to "dd-MM-yyyy". Currently, my entity code looks like this: @IsOptional() @ApiProperty({ example: '1999-12-12', nullable: true }) @Column({ type: 'date', nullable: true } ...

Using a function with a parameter as an argument in an event handler

Imagine you have the code snippet below: $('#from').focus(listExpand(1)); $('#to').focus(listExpand(3)); I am facing an issue as the code is not behaving as expected. I believe the problem lies in passing a function result instead of ...

When I attempt to run several promises simultaneously with Promise.All, I encounter an error

My code contains a series of promises, but they are not being executed as expected. Although the sequence is correct and functional, I have found that I need to utilize Promise.all in order for it to work properly. dataObj[0].pushScreen.map(item => { ...

Code written in Javascript runs before any CSS files are downloaded and processed

While researching async scripting in web applications, I stumbled upon an interesting article. Essentially, it suggests that JavaScript scripts are not executed until all stylesheet CSS files are downloaded and parsed. Intrigued by this concept, I decided ...

Tips for maintaining the fixed size of a table header and preventing it from resizing in width

My goal was to create a table using divs with fixed headers while scrolling vertically. However, I encountered an issue where the header width seemed to shrink and became misaligned with the rows. Even setting the width to 100% did not resolve this probl ...

Tips for saving HTML data locally

Is there a way to persist my HTML element tag data even after the user closes the browser? For example: <div class="classOne" data-random="50"> If I use jQuery to change the data attribute like this: $(".classOne").attr("data-random","40") How ca ...

Click on the next tab within the ExtJS tab menu

I am looking to deactivate a tab and if it happens to be active, I want the system to automatically switch to the next tab. I attempted myPanel.tab.disable(); if(myPanel.tab.active) myPanel.NextSibling().tab.setActive(); and myPanel.tab.disable(); ...

Clicking the React Todo Delete Button instantly clears out all tasks on the list

I am dealing with 2 files: App.js import React, { Component } from 'react'; import './App.css'; import ToDo from './components/ToDo.js'; class App extends Component { constru ...

Incorporate new markers into Google maps without the need to constantly initialize the map

My current goal is to have the user input a latitude and longitude into a text box, and then display a marker on the map for that location without needing to reinitialize the map each time. To start, I have set up my map like this: <script type="text/ ...

Is there a way to change the color of a specific tab without affecting the content within it

I am attempting to change the color of an individual tab using jQuery. However, when I set the background attribute in CSS, it colors the entire background instead. What specific property should I be setting to only change the color of the tab itself? ...

What is the best way to include two class names within a single div using Next.js?

Struggling to include two different CSS classes into a single div element, I encountered some issues. For reference, here is a screenshot: https://i.stack.imgur.com/UuCBV.png https://i.stack.imgur.com/sHNwq.png My code snippet looks like this: blog.js ...

Encountering an issue with state setting - Experiencing an excessive amount of re-renders in a

If you want to see the solution in action, check out the Code Sandbox link provided below for better clarity on the issue at hand. Currently facing an issue with setting my mymoviegenreobjects as the mymoviegenreinfo state within the useFetchMovieGenreRes ...

Managing additional components in request JSON when communicating with DialogFlow, previously known as Api.ai

My current challenge involves enhancing the information sent in a JSON request from my application to DialogFlow. While I am familiar with triggering events to send data calling an intent through the method described in Sending Parameters in a Query Reques ...