reactjsreddit

How to make images render in React app using Reddit API


I've managed to get my React app to display the title of Reddit articles but the images are not displaying.

Any ideas where I'm going wrong? Here's my code:

App.js
import './App.css';
import { useState, useEffect } from 'react';
import NavBar from './components/NavBar/NavBar';
import Card from './components/Card/Card';

function App() {
  //default values of useState() hooks are an array and hot
  //useState is an empty array
  const [articles, setArticles] = useState([]);
  const [subreddit, setSubreddit] = useState("popular");

  //every time subreddit changes, useEffect() will recall
  useEffect(() => {
      fetch("https://www.reddit.com/r/popular.json?limit=10").then(response => {
          if (response.status !== 200) {
              console.log("Error!")
              //return out of the function
              return;
          }
          //parse the response from the server through JSON
          //this returns a promise so we have to call .then()
          response.json().then(data => {
              if (data !== null) {
                  //setting articles equal to the array of children
                 setArticles(data.data.children);
                 //console.log(data.data.children);
              }
          });
      })
      //every time, subreddit changes, the useEffect() hook will recall
  }, [subreddit]);
  
  return (
    <div className="app">
      <header>
        <div className="nav-bar-container">
          <NavBar/> 
        </div>
      </header>
      <div className="articles">
      {/*Looping through the articles: if articles is not equal null, map through the articles array and get the article
      and index of the article. We then get the article which has a key of index. 
      Then we pass through the data of each article as a prop*/}
          {
            (articles !== null) ? articles.map((article, index) => <Card key={index} article={article.data}/>) : ''
          }
          
      </div>

    </div>
  );
}

export default App;
Card.js
import "./Card.css";

//pass through props to get our titles
const Card = (props) => {
        
    return (
            <article className="reddit-post">
                {/*Accessing title and image of post */}
                    <h3>{props.article.title}</h3>
                    <div className="image">
                    {props.article.preview ? <img src={props.article.preview.images[0].source.url}/> : null}
                    </div>
                    

            </article>
    )
}

export default Card;

What I see on the page:

Image not appearing in Reddit React app

I've tried adding the getUrl() function here but wasn't sure how to connect it to my app. This is all still rather new to me. Any help would be greatly appreciated!


Solution

  • When I tried directly accessing the preview url

    Ex: https://preview.redd.it/fi3fdlpxyw4d1.jpeg?width=960&amp;crop=smart&amp;auto=webp&amp;s=2e7d775f4333b74fd2f89a2c5fc50373aa4fef38

    I see that a 403 Forbidden response is being sent by reddit, basically reddit might be preventing access to the urls for preview.

    Instead you could try using the url or thumbnail property like props.article.thumbnail or props.article.url, they seem to load the image without access issues.