HTML elements have a delayed rendering process in ReactJS

As I dive into learning ReactJS by creating a ReactJS version of my blog, I encountered an interesting issue while testing Google Page Speed. The recommendation to "prioritize visible content" led me to add a placeholder article with a loading message, lorem ipsum description, and a default header image. However, when retesting the page speed, I found that the title, image, and description of the placeholder article were not being rendered. It's puzzling to me why this static text isn't showing up, even after simulating a slow internet connection.

If you want to take a look at the code, it's available on GitHub: https://github.com/erikkubica/reactjs-simple-blog-test. Check out the src/modules/article/ArticleListItemPlaceholder.js and ArticleList.js files for more details.

In addition to the rendering issue with the placeholder article, I also noticed that the logo was missing. This discrepancy between my ReactJS site and a non-React website is confusing, especially since the styles and navigation component are loading correctly.

If you'd like to see the problem in action, visit:

Here's a screenshot of the problem for reference: https://i.sstatic.net/rwqiG.png

I appreciate any explanations, good practices, or tips you may have to offer for further learning.

UPDATE: I was able to resolve the problem.

The issue stemmed from the fact that custom fonts were not loading, causing the text to become invisible. Adding fontFamily: "Arial" to the inline styles of the elements fixed the problem. Special thanks to Mr. Lister for the assistance.

And a big shoutout to John Ruddell for sharing some best practices.

Answer №1

The problem you're facing is that you're setting state asynchronously but trying to render things in a semi-synchronous manner.

async fetchData() {

    //const response = await fetch("/static/articles.json");

    let data = null; //await AsyncStorage.getItem('@MySuperStore:articles_storage_' + this.state.category);

    if (data === null) {
        const response = await fetch("https://www.netlime.eu/wp-json/get-posts/v2/all/");
        data = await response.json();
        await AsyncStorage.setItem('@MySuperStore:articles_storage_' + this.state.category, JSON.stringify(data));
    }

    try {
        data = JSON.parse(data);
    } catch (e) {

    }
// The issue lies here
______________________________________________
    this.setState({articles: data});

    this.createArticleList();
______________________________________________

// Change this to the following
    this.setState({articles: data}, () => {
        this.createArticleList();
    });
}

Since setState is asynchronous, you're creating the articleList state item before the articles are set on state, causing the UI to not update.

Edit

It's recommended not to use a secondary state variable to hold an array of articles to be rendered. Instead, create them dynamically.

export default class ArticleList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            articles: [],
            category: this.props.category ? this.props.category : 0
        };
    }

    async fetchData() {
        let data = null; //await AsyncStorage.getItem('@MySuperStore:articles_storage_' + this.state.category);
        if (data === null) {
            const response = await fetch("https://www.netlime.eu/wp-json/get-posts/v2/all/");
            data = await response.json();
            await AsyncStorage.setItem('@MySuperStore:articles_storage_' + this.state.category, JSON.stringify(data));
        }

        try {
            data = JSON.parse(data);
        } catch (e) {

        }

        this.setState({articles: data});
    }
    componentDidMount() {
        this.fetchData();
    }
    render() {
        const articles = this.state.articles.map((article) => {
            return (
                <ArticleListItem
                    key={article.ID}
                    article={article}
                />
            );
        });

        return (
            <div>
                { articles.length ? articles : <ArticleListItemPlaceholder/>}
            </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

Attempting to execute a function within a MAP operation

My attempt to integrate a function into my map is resulting in only the function running and not the rest of the code. Edit: After reflecting on the situation, it dawned on me that I need to elaborate further. The goal here is to execute this.math in orde ...

I need to implement a div-based dropdown with a scrollbar in JavaScript and CSS to prevent it from extending beyond the screen. Additionally, the use of struts is essential in this implementation

Dealing with a dynamically populated div-based dropdown can be tricky, especially when it extends beyond the screen's limits and hides entries. This is an inherited application that lacks support, leaving me to handle it without the necessary expertis ...

Implementing beans within an HTML form action allows for seamless communication between the form and

I am seeking assistance as I am unable to locate any tutorials online for the issue I am facing. How do you go about using a <bean:write....> within a <html:form....> The code I have written is: <html:form action="/restricted/client/so ...

Preventing the use of double-click on Grooveshark

I am currently in the process of creating a webpage to serve as a jukebox for parties. My goal is to have the page load Grooveshark with a transparent overlay (or any other necessary method) that can prevent users from forcefully adding their song to the f ...

What is the best way to scale a div proportionally within a bootstrap grid?

Despite spending hours reading numerous online sources, I am still struggling to fully grasp the CSS/HTML box model. Specifically, I am attempting to create sections with a ratio of 3:2, where 3 represents the width and 2 represents the height. https://i.s ...

Please send the element that is specifically activated by the onClick function

This is the HTML code I am working with: <li class="custom-bottom-list"> <a onClick="upvote(this)"><i class="fa fa-thumbs-o-up"></i><span>upvote</span></a> </li> Here is my JavaScript function for Upvot ...

The value of the React prop has not been defined

I'm just diving into the world of React and trying to grasp the concept of passing props between components. Specifically, I am attempting to send the prop "buttonText" to another component called "name" in my code. Here is a snippet of my code: class ...

Show or hide a div based on the visibility of another div in Angular using *ngIf

Looking for a way to dynamically display images based on the visibility of another image? Consider the code snippet below: <div *ngFor="let badge of user.progress.unlockedBadges"> <img id="{{i}}_unlockedImage" *ngIf="badge == achievemen ...

Aligning content within a div using Bootstrap 4

For a demonstration of this code, please visit the following Codepen link: codepen <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/> <script src="https://maxcdn.bootstrapcdn.com/bootstr ...

Decorative initials have a tendency to create spaces within the text

I have incorporated Google Fonts into my website, along with Bootstrap. Here is the code I am using: .initial { font-size: 1.5em; font-family: 'Euphoria Script', cursive; } p { font-family: 'Open Sans', sans-serif; } <html> ...

Encountering an issue with accessing the URL http://localhost:3000/api/products as it returns a 404 (Not Found)

Among the plethora of StackOverflow questions addressing this error, none seem to provide a solution that works for me. I am utilizing react with redux in an attempt to fetch products. My node backend server is running on port 5000, and I am using concur ...

Trouble with HTML2PDF.js - download not being initiated

Currently, I am utilizing html2pdf.js in my project by following this tutorial: https://github.com/eKoopmans/html2pdf.js However, I've encountered an issue where despite implementing everything as instructed, the download prompt for the specified div ...

Unable to delete product from shopping cart within React Redux reducer

Currently, I am tackling the challenge of fixing a bug in the shopping cart feature of an e-commerce website I'm working on. The issue lies with the remove functionality not functioning as expected. Within the state, there are cartItems that can be ad ...

Tips for positioning a Material UI Button and TextField side by side, perfectly aligned on the same line and height

I am currently working on aligning a <Button> from the Material UI library so that it is positioned at the same height as the <TextField> next to it and perfectly aligned with that field. Both the <Button> and the <TextField> are e ...

Whenever I try to open my jQuery UI Dialog without first displaying an alert, it does not work

Beginning of my HTML page, initializing a dialog : <script type="text/javascript"> $(function() { $( "#dialog-confirm" ).dialog({ autoOpen: false, resizable: true, height:180, width:300, modal: true, buttons: { "Yes": ...

Differentiate the items within a list containing identical divs using JavaScript

Currently, I am expanding my knowledge in HTML, CSS, and JS by incorporating Angular and JQuery. In one of my projects, there is a div labeled "eventBoxes" where multiple divs known as "eventBox" can be added. I have created a template for the eventBox i ...

Design a sophisticated background using CSS

https://i.sstatic.net/yILwL.png I am wondering if there is a way to create a CSS3 background similar to the one shown in the image link above. The gradient should smoothly transition from white to black, spanning across a header div, and remain consistent ...

"Enhancement in Chrome: Inclusion of Origin header in same-origin requests

When we POST an AJAX request to a server running locally, the code looks like this: xhr.open("POST", "http://localhost:9000/context/request"); xhr.addHeader(someCustomHeaders); xhr.send(someData); The webpage where this javascript is executed is also on ...

Struggling to locate the distinctive XPath for the button

I am facing a situation where the XPath is non-unique and identifies 3 elements on the page that change positions upon refresh: <div class="col-xs-12 Hover"> <button data-testid="continueCheckoutButton" ng- class="continueDellMetricsC ...

Shifting the position of personalized tabs using Jquery

I have created some basic HTML/CSS tabs and I want to move to the next tab by clicking a link at the bottom of every tab. HTML <ul class="tabs"> <li class="active"> <a href="#">Explainer (2mins)</a> <div class=" ...