Display image from API In React

Viewed 14303

I am trying to display an image from my API. The code I am using so far does not seem to work, in the src of the image it shows just the string not the image i.e <img src="{data.home[0].image}" alt="image">.

My code so far is:

  import React, { Component } from 'react';
  import '../main/main.css';

  class Main extends Component {
      constructor() {
          super();
          this.state = {
              name: 'React',
              awsApiData: [],
          };
      }

      componentDidMount() {
          console.log('app mounted');
          /*global fetch */
          fetch('https://onelbip0e6.execute-api.eu-west-2.amazonaws.com/livestage/xxxx')
              .then(data => data.json())
              .then(data => this.setState({ awsApiData: data }, () => console.log(data)));
      }

      render() {
          const data = this.state.awsApiData;
          return (
              <div className="main-content container">
           {(data && data.home) &&
              <div><h2>{data.home[0].title}</h2><br /><p>{data.home[0].body}</p>
              <img src="{data.home[0].image}" alt="image"></img>
              </div>
          }    
      </div>
          );
      }
  }
  export default Main;
2 Answers

You are assigning the value of string to img src so it will give the output as string only.

You need to use curly braces to embed a JavaScript expression in an attribute.

So try changing

<img src="{data.home[0].image}" alt="image">

to (Remove the quotes around curly {} brackets)

<img src={data.home[0].image} alt="image">

Don’t put quotes around curly braces when embedding a JavaScript expression in an attribute. You should either use quotes (for string values) or curly braces (for expressions), but not both in the same attribute.

Reference Link here..

Please post your api response as well.

See if changing src="{data.home[0].image}" to src={data.home[0].image} helps

Related