12

I Have local API which contains many objects in every object there is one image like this:

{
created_at: "2022-09-10T19:40:24.000000Z"
id: 2
service_id: 1
state_image: "202209101955Screenshot (303).png"
state_text_ar: "agaga"
state_text_en: "afgagfa"
state_title_ar: "nice"
state_title_en: "idaljflia"
state_title_secondary_ar: "gagag"
state_title_secondary_en: "afaf"
updated_at: "2022-09-10T19:55:43.000000Z"
}

The problem: when I call state_image to display the image it not showing up.

react code :

React.createElement("div", {
      className: "slideContent",
      style: {
        backgroundImage: `url('${slide.state_image}')` }
 }

enter image description here

as you see in the background image (there is an image) but nothing display in the screen

1
  • It seems there's a problem with the image path. Check if the image is in the root directory or a specific folder. If it's in a folder, make sure to include the folder name in the path. This should display the image correctly. Commented Jul 27, 2023 at 14:11

2 Answers 2

17

To fetch image from API with React, we can use the fetch function.

For instance, we write:

import React, { useEffect, useState } from "react";
const imageUrl = "https://i.imgur.com/fHyEMsl.jpg";

export default function App() {
  const [img, setImg] = useState();

  const fetchImage = async () => {
    const res = await fetch(imageUrl);
    const imageBlob = await res.blob();
    const imageObjectURL = URL.createObjectURL(imageBlob);
    setImg(imageObjectURL);
  };

  useEffect(() => {
    fetchImage();
  }, []);

  return (
    <>
      <img src={img} alt="icons" />
    </>
  );
}

We call fetch with the imageUrl to make a GET request to it.

Then we call res.blob to convert the response object to a blob.

Next, we call URL.createObjectURL with the imageBlob to convert it to a URL string that we can set as the src attribute of the img element.

Finally, we call setImg with imageObjectURL so we can set img as the value of src to display it.

Conclusion To fetch image from API with React, we can use the fetch function.

Sign up to request clarification or add additional context in comments.

3 Comments

i did all that but i didn't share it
can you add your fetch funtion
const [slides, setSlides] = useState([]) const id = Number(window.location.pathname.replace('/states/','')) useEffect(()=>{ fetch("127.0.0.1:8000/api/state/show") .then(res => res.json()) .then(data => setSlides(data.filter((x) => x.service_id !== id))) },[])
0

change to this:

React.createElement("div", {
      className: "slideContent",
      style: {
        backgroundImage: `url(${slide.state_image})` }
 }

1 Comment

i did it and noting happend

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.