3

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;
4
  • 3
    Can you try changing src="{data.home[0].image}" to src={data.home[0].image} .. Remove double quotes around the curly brackets.. Commented Mar 10, 2020 at 16:44
  • That worked, cant believe it was the speech marks, Can you add answer and I can mark as correct Commented Mar 10, 2020 at 16:45
  • 1
    " " is always a string. {} is JSX syntax for a javascript expression. To use a variable within JSX you must use the {} syntax, and not from within a string. Commented Mar 10, 2020 at 16:46
  • @Sole, Answer has been added added.. Commented Mar 10, 2020 at 16:49

2 Answers 2

5

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..

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

Comments

1

Please post your api response as well.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.