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;
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With