1

I'm a React noob and I'm making an API request to retrieve JSON from a movie API and then displaying information about the movies, including the movie poster, in my component. I was able to retrieve and display text, but I am having trouble displaying images using JSX and the URL of the database.

I've assigned the images to post.poster_path and I'm attempting to concatenate the rest of the URL to the JSX.

<img src={"https://image.tmdb.org/t/p/w300/"+post.poster_path} alt="Movie Poster"/>

This doesn't work.

poster_path contains the image, I have verfied this in React tools. How do I properly concatenate the rest of the URL to post.poster_path?

4
  • Can you tell us what src ends up being when you inspect it? "This doesn't work" should be a more verbose description of what exactly happens. Commented Dec 9, 2017 at 5:19
  • The image doesn't display at all because I am assuming the concatenation is incorrect. The alt tag "Movie Poster" displays. Commented Dec 9, 2017 at 5:34
  • Yes, the image doesn't show, but can you inspect the element with chrome web tools (etc.) and tell us what ends up being the src? I haven't used react in a few months, so nothing looks wrong, but that's how I'd start. Commented Dec 9, 2017 at 6:49
  • Try using require: <img src={require("image.jpg")} /> Commented Dec 9, 2017 at 7:01

1 Answer 1

2

If

post.poster_path = 'image.png'

and the whole url is

https://image.tmdb.org/t/p/w300/image.png"

for your image then the img tag will be as follows

<img src={`https://image.tmdb.org/t/p/w300/${post.poster_path}`} alt="Movie Poster"/>

In JSX if you have a value in variable and need to concat with a string you use tick `

eg. {`string ${variableName}`}

and if post.poster_path has the whole path then:

<img src={post.poster_path} alt="Movie Poster"/>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.