Home > Software design >  Can't display image from Strapi in ReactJS (frontend)
Can't display image from Strapi in ReactJS (frontend)

Time:04-04

I can't show the images from Strapi to my ReactJS (frontend).

This is my Homepage code:

import React from "react";
import useFetch from "../hooks/useFetch";
import { Link } from "react-router-dom";

export default function Homepage() {
  const { loading, error, data } = useFetch(
    "http://localhost:1337/api/reviews"
  );


  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;

  console.log(data);

  return (
    <div>
      {data.data.map((review) => (
        <div key={review.id} className="review-card">
          <h1>{review.attributes.title}</h1>
          <img src={'http://localhost:1337/api/reviews?populate=reviewImage'} alt={"Not Working!"}/>
        </div>
      ))}
    </div>
  );
}

This is the output:

enter image description here

This is the data I'm getting in postman:

enter image description here

CodePudding user response:

I'm not sure if I'm missing something, but I don't see any attribute that relates to an image URL.

  1. you fetch the data from http://localhost:1337/api/reviews

  2. you iterate over the data within the return statement

  3. from glancing over your iteration, you point the src to http://localhost:1337/api/reviews?populate=reviewImage although, http://localhost:1337/api/reviews doesn't seem to have any attribute that contains an image.

furthermore, unless that API endpoint returns the image itself, that source is incorrect.

My Suggestion:

if it's possible to modify whatever API you're using, i'd do something along this route:

append the direct image URL link to the response you get from http://localhost:1337/api/reviews once you've done so, you'd be able to target it just like you did with the title and do something like that:

      {data.data.map((review) => (
        <div key={review.id} className="review-card">
          <h1>{review.attributes.title}</h1>
          <img src={review.attributes.image} alt={...}/>
        </div>
      ))}
    </div>```


CodePudding user response:

isn't it review.Image not reviewImage ?

  • Related