Adding an image to a React component in your project

I am currently working on an app that utilizes React and Typescript.

To retrieve data, I am integrating a free API. My goal is to incorporate a default image for objects that lack images.

Here is the project structure:

https://i.stack.imgur.com/xfIYD.png

Within movies.service.tsx, I am fetching the data and assigning the value retrieved from the DB to the picture property of the movie object. If there is no value present, I intend to assign it the path leading to default-poster.png:

import * as img from '../images/default-poster.png';

console.log('img ', img);

const movieApiBaseUrl = "https://api.themoviedb.org/3";
const posterBaseUrl = "https://image.tmdb.org/t/p/w300";
export interface Movie {
    id: number;
    title: string;
    rating: number;
    description: string;
    picture?: string;
    date: string;
  }

  export function fetchMovies(): Promise<Movie[]> {
   return fetch(
     `${movieApiBaseUrl}/discover/movie?sort_by=year.desc&api_key=${process.env.REACT_APP_API_KEY}`
   )
     .then((res) => res.json())
     .then((res) => mapResult(res.results))
     .catch(() => {
         return [];
     });
 }

 // = movie has to be after const {} here
 function mapResult(res: any[]): Movie[] {
   return res.map((movie) => {
     const {
       id,
       title,
       vote_average,
       overview,
       poster_path,
       date,
     } = movie;
     return {
       id: id,
       title: title,
       rating: vote_average,
       description: overview,
       picture: poster_path ? `${posterBaseUrl}${poster_path}` : img,
       date: date,
     };
   });
 }

However, I encountered an issue when trying to assign img to the picture property in Typescript. Upon console logging the img value, I discovered that it represents a module:

Module default: "data:image/png;base64,iVBORw0KGgoAAAA <...>" Symbol(Symbol.toStringTag): "Module" esModule: true __proto: Object

In order to utilize these paths in the MovieCards.tsx component in the future, I must find a solution to properly assign them to the picture property.

What steps should I take to address this challenge?

Your assistance is greatly appreciated!

Answer №1

To fix the issue, include the default image by importing it into the movies.service.tsx file:

import defaultImage from '../images/default-poster.png';

Next, use the defaultImage variable as the fallback in the ternary operator:

picture: poster_path ? `${posterBaseUrl}${poster_path}` : defaultImage,

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generate a Jest dummy for testing an IncomingMessage object

I am facing a challenge in writing a unit test for a function that requires an IncomingMessage as one of its parameters. I understand that it is a stream, but I am struggling to create a basic test dummy because the stream causes my tests to timeout. : T ...

How can we fix the null parameters being received by the ModelPage function?

I've been learning how to successfully pass values to a Post method using AJAX in .NET Core 6 Razor Pages, but I am encountering some difficulties. Below are the relevant codes: Front end: function calculateSalary() { var dropdown = document.get ...

Deduce the generic types of conditional return based on object property

My goal is to determine the generic type of Model for each property. Currently, everything is displaying as unknown[] instead of the desired types outlined in the comments below. playground class Model<T> { x?: T } type ArgumentType<T> = T ...

Is it possible to adjust responsiveness within the styled() function in Material-UI version 5 (MUI

Is it possible to utilize the responsiveness of MUI inside the styled() function? For instance: import { Button } from "@mui/material"; import { styled } from "@mui/system"; const MyButton = styled(Button)(({ theme }) => ({ wid ...

Execute function prior to redirection of iframe

I have a specific challenge with an iframe on my webpage. I am looking to trigger a function right before the iframe reloads a new page, rather than after it has finished loading. I need this function to be triggered before the iframe redirects to the new ...

Create an Ajax request function to execute a PHP function, for those just starting out

I came across a JS-Jquery file that almost meets my needs. It currently calls a PHP function when a checkbox is clicked, and now I want to add another checkbox that will call a different PHP function. My initial attempt was to copy the existing function a ...

Could you provide some advice for creating a Single Page website?

I am working on a simple HTML setup with various elements such as a navbar and content blocks. <html> <head> <title>My HTML5 App</title> <meta charset="UTF-8"> <meta name="viewport" content="wid ...

Connect guarantees while generating template

Fetching data through a function. Establishing a connection and retrieving necessary information. Some code has been omitted for brevity. function executeSQL(sql, bindParams , options) { return new Promise(function(resolve, reject) { ... resolv ...

Error: Conversion of "2018-01-01-12:12:12:123456" to a date is not possible for the 'DatePipe' filter

<td>{{suite.testSuiteAttributes && suite.testSuiteAttributes.modifiedTimestamp | date: 'yyyy-MM-dd' }} </td> I am trying to display the date in the "05-Feb-2018 11:00:00 PM CST" CST format, but I keep getting an ...

Unexpected issue with sliding menu toggle implementation

I have been struggling to make a menu slide to the left when a button is clicked, and then slide back to its original position when the same button is clicked again. Although I have been using the toggle method, it doesn't seem to be working for me. I ...

Monitoring of access controls on Safari during uploads to S3

Safari 10.1.2 Encountering an issue intermittently while attempting to upload PDF files to S3 using a signed request with the Node aws-sdk. Despite working smoothly 90% of the time, have been pulling my hair out trying to resolve this problem. Could it be ...

Stop JavaScript Injection Attacks

Let's consider a scenario where a user inputs information into a form that is then submitted to the server using PHP. In the PHP code, we have: $data = $_POST['data']; // or $data = strip_tags(@$_POST['data']); I am curious t ...

Tips for resolving the issue of invalid functions as a child component in React

When I call a function that returns HTML code, everything works fine until I try to pass a parameter in. At that point, I receive an error saying "Functions are not valid as a React child." The issue is that I need to access the props from this function. T ...

Encountering the error message "Unable to access property 'addEventListener' of null while trying to manipulate innerHTML"

Currently, I am utilizing innerHTML to include certain elements and a wrapper around them. for (i = 0; i < arr.length; i++) { b.innerHTML += "<div class='wrapper'><div class='col-4'>" + arr[i].storeID + "</div> ...

Whenever I implement JavaScript validation on my HTML page, it causes the page to become un

Whenever I try to enter more than 30 to 40 characters in the password input field on my HTML page, all web browsers become unresponsive. This issue persists even if I modify the minimum length and other requirements to 50. I am new to JavaScript. <!D ...

What is the process for configuring the avatar in the material-ui card component?

I am currently utilizing the CardHolder component from material-ui, which can be found at https://material-ui.com/api/card-header/. Within my project, I have this image: src/img/apple.svg In an attempt to set the avatar image, I tried the following code ...

prevent unnecessary duplicate database queries for generating metadata in the upcoming 13 or 14 instances

In the latest updates, version 13 and 14 of Next introduced the usage of the generateMetadata function as the preferred method to define all page metadata. However, a drawback of this approach is that because of the separation of logic, fetching data base ...

tips for using Node Mailer to send emails without using SMTP

Currently, I am facing an issue with sending emails through nodemailer. Although I have successfully used my gmail account for this purpose in the past, I now wish to switch to using my business email to communicate with clients on a regular basis. The cu ...

Symfony: The Database Query Button with a Pop-up Feature

I am looking to create a button that will automatically search my database for all users with a "secouriste" attribute set and display their first name, last name, and phone number in a popup. After conducting research, here is what I have gathered: In m ...

Utilizing internal PDF links in a Microsoft UWP application

In the process of developing a UWP app using javascript, I have created a list of links that are connected to PDF files stored locally in the app. The ultimate goal is to offer a collection of hands-free documentation for the Hololens (Windows AR) device. ...