Home > Back-end >  How to display actual image instead of image-link from JSON in react
How to display actual image instead of image-link from JSON in react

Time:11-26

I tried to display my image from JSON on the page but instead of the image, I get the link. How to fix that?

I have tried using:

<div id="test">
      <img src={data[0].image}/>
    </div>

But it doesn´t work. There is something called State but I really have no idea how to use that.

My Code:

import React from 'react'

function Coffee() {
 
  const baseURL = 'https://api.sampleapis.com/coffee/hot';
  fetch(baseURL)
  .then(resp => resp.json())
  .then(data => displayData(data[0].image));

function displayData(data) {
  document.querySelector("#test").innerHTML = JSON.stringify(data, null, 2);
} 

  return (
      <div id="test">
        <img src="??"/>
      </div>
    
  )
}
export default Coffee

CodePudding user response:

Use a state called imageURL for example with the help of useState from React like below. That's the correct React way I would say.

You will see some additional HTML and JavaScript code. That's so we have a working example here on Stack Overflow. What really matters here is the Coffee function.

function Coffee() {
  const [imageURL, setImageURL] = React.useState("");

  React.useEffect(() => {
    const baseURL = "https://api.sampleapis.com/coffee/hot";
    fetch(baseURL)
      .then((resp) => resp.json())
      .then((data) => setImageURL(data[0].image));
  }, []);

  return (
    <div id="test">
      <img src={imageURL} alt="" />
    </div>
  );
}


ReactDOM.render(
  <Coffee />,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

  • Related