-1

I have an app that displays images from an API. However some of the items don't have the required backdrop_path.

How would I display a different image if the original is not available

Here's my code

const MovieItem = ({ movie }) => {
  const imagePath = 'https://image.tmdb.org/t/p/w500';

  return (
        <img src={`${imagePath}${movie.backdrop_path}`} alt={movie.title} />

I want the img to be {movie.poster_path} but only if {movie.backdrop_path} is null or not existent.

Or alternatively a hard coded image to display instead.

DGB
  • 1,252
  • 2
  • 16
  • 32

4 Answers4

1

here's an answer for React, using a ref to allow the component to modify the image's source if it errors (i.e. the image specified by prop 'src' doesn't exist). In this example the fallback image is hard-coded, but could also be a prop etc.

import { useRef } from 'react';

const imageWithFallback = ({ src }) => {
  const imgRef = useRef();
  const onImageError = () => imgRef.current.src="/fallback-image.png";
  return (
    <img ref={imgRef} src={src} onError={onImageError} />
  )
}
Andy Lorenz
  • 2,905
  • 1
  • 29
  • 29
0

you can try use img's onerror event, it will be fired when it failed to load the resource.

0

You can use conditionally paths like this:

const MovieItem = ({ movie }) => {
  const imagePath = 'https://image.tmdb.org/t/p/w500';
  const src = ${movie.backdrop_path} === null || ${movie.backdrop_path} === 
              undefined ? {movie.poster_path} : ${movie.backdrop_path} 

  return <img  src={src} alt={movie.title} />
}
Ronak Lalwani
  • 376
  • 2
  • 9
0

<img src={`${imagePath}${movie.backdrop_path || movie.poster_path}`} alt={movie.title} />

You can use conditional statements for images.

DGB
  • 1,252
  • 2
  • 16
  • 32