Some images won't load on browser. How can I preload all of my images in React JS?

32 Views Asked by At

When I load my react page, some images aren't showing up because of a 403 error. Most images are loading however. I think this is because the browser isn't able to load all the images I have without preloading. For context, I currently have a flask backend that sends data (including image urls) to the react frontend.

Here is my code for the react part:

import React, { useState, useEffect } from 'react'
import NewsItem from "./components/NewsItem"
import './App.css';

function App(){
  const[data, setData] = useState([])

  useEffect(() => {
    fetch("/sentiment").then(
      res => res.json()
    ).then(
      data => {
        setData(data.articles)

        
      }
    )

  }, [])


  console.log(data.urlToImage);

  var mapped = data.map(article => <NewsItem 
    author={article.author}
    content={article.content}
    description={article.description}
    publishedAt={article.publishedAt}
    sentiment={article.sentiment}
    source={article.source.name}
    title={article.title}
    url={article.url}
    urlToImage={article.urlToImage}
  />);

  return (
    <main>
      <div className = "cards-container container flex">
         {mapped}
      </div>
    </main>
      
    )
}

export default App

Here is my code for the newsitem component which is where the image tag is:

import React from "react"
import HtmlRenderer from '../HtmlRenderer';
import './newsItem.css'

const NewsItem = (props) => {
    function componentDidMount() {
        const newImage = new Image();
        newImage.src = props.urlToImage;
        window[props.urlToImage] = newImage;
        
    }
    componentDidMount();
    var replacementURL = "https://via.placeholder.com/400x200"
    return (
            
            <div className = "card">
                <div className="card-header">
                    <img src = {props.urlToImage} alt = {replacementURL}/>
                </div>
                <div className = "card-content">
                    <h3>
                        <a href = {props.url}>
                            {props.title}
                        </a>
                    </h3>
                    <h6 className="news-source" id="news-source">{props.source} {props.publishedAt}</h6>
                    <p id = "news-description">
                        <HtmlRenderer htmlString={props.description} />
                    </p>
                    <h1>Sentiment: {props.sentiment}</h1>
                </div>
                
            </div>
        
    )
}

export default NewsItem

As you can see, in the newsItem section, I tried a component loader (the "componentMount" method) that I saw somewhere else, but it didn't work. Can someone help me figure out how to fix this image loading problem?

0

There are 0 best solutions below