Display image from API In React
Solution 1
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.
Solution 2
Please post your api response as well.
See if changing src="{data.home[0].image}" to src={data.home[0].image}
helps
Related videos on Youtube
Sole
Updated on May 30, 2022Comments
-
Sole almost 2 years
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;
-
Maniraj Murugan about 4 yearsCan you try changing
src="{data.home[0].image}"
tosrc={data.home[0].image}
.. Remove double quotes around the curly brackets.. -
Sole about 4 yearsThat worked, cant believe it was the speech marks, Can you add answer and I can mark as correct
-
Brian Thompson about 4 years
" "
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. -
Maniraj Murugan about 4 years@Sole, Answer has been added added..
-