Using TypeScript, pass an image as a prop in a Styled Component

I am facing an issue with the code below that is supposed to display the "NoBillsLaptopPNG.src" image on the screen, but for some reason, the image is not showing up.

The images are being imported correctly, so I'm unsure why the image is not appearing as expected.

import NoBillsMobilePNG from "../../public/assets/quotes/no-bills-mobile.png"
import NoBillsLaptopPNG from "../../public/assets/quotes/no-bills-laptop.png"

export const NoBillsSummary = () => {
  return <div>
    <TestImg
      NoBillsMobilePNG={NoBillsMobilePNG.src}
      NoBillsLaptopPNG={NoBillsLaptopPNG.src}
    ></TestImg>         
  </div>;
};

const TestImg = styled.img<{
  NoBillsMobilePNG: string;
  NoBillsLaptopPNG: string;
}>
// the src of the image is passed in as props because a media query will be added later to switch between images

src: url(${(NoBillsLaptopPNG) => NoBillsLaptopPNG.src});

width : 126.07px;
height : 107.59px;
margin-top: 2px;
`;

Answer №1

When utilizing the TestImg component, you pass src as props to NoBillsLaptopPNG.

A more appropriate name for props would be NoBillsLaptopPngSrc.

If you are styling TestImg, the input parameter for NoBillsLaptopPNG is already src. Therefore, referencing its src field again is redundant.

Consider this alternative approach:

 src: url(${(NoBillsLaptopPNG) => NoBillsLaptopPNG});

Answer №2

When using styled-components, if you include a function in your style, it will be executed with the entire set of props from the component.

As a result, you need to specify a specific member or destructure it, similar to how you would with a regular React Function Component.

It's important to note that changing the src attribute of an <img> tag through CSS alone is typically not possible. However, altering its content is still achievable.

As mentioned by @forlift's response, you are already passing the .src value as a prop, so there is no requirement to access it again.

const TestImg = styled.img<{
  NoBillsMobilePNG: string;
  NoBillsLaptopPNG: string;
}>`
  // Destructuring the props here
  content: url(${({ NoBillsLaptopPNG }) => NoBillsLaptopPNG});

  width : "226.07px";
  height : "207.59px";
  margin-top: "2px";
`;

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

Is there a way to reach a different function within the value of the react Context.Provider?

Right now, I am learning how to utilize the react context API. Within my react Provider class, I have some state data and functions stored in the value={}. But I am curious, how can I call a function inside this value from another function within the same ...

"Mastering the power of ReactJS with Promise.all

I'm struggling to ensure 'studentDataPromise' resolves before 'fetchLoansPromise'. It's crucial to fetch the student data first in order to fetch the loans. Any insight on what might be causing this issue? Current Status: t ...

Exploring the power of V-for with checkboxes in VueJS

One issue I am facing is related to triggering my save method only when a checkbox is selected or true in Vue JS. I have no problem listing values and saving them to the database using axios, Vue JS, and Spring Boot. However, every time I click the checkbo ...

Ways to insert data in angularjs

As I attempt to add data to a list using the addGroup function, I encounter a type-error. The error message reads: "TypeError: Cannot read property 'push' of undefined" at r.$scope.addGroup (main.js:7) at fn (eval at compile (angular ...

When a model.find is passed as an argument to be invoked, it results in an error

After working with ExpressJS for a while, I decided to explore using Mongoose alongside it. In the callback of my queries where I handle errors like this: function( error, data ) {...} , I found myself repeating code. To streamline this process, I created ...

Tips for resolving the problem with a malfunctioning ChartJS legend

I have been working on my project using chartjs and all the charts are displaying correctly except for the legends. No matter what I try, the legend is not showing up. Here's the code snippet: var ctx1 = document.getElementById("chart1").getContext(" ...

Issues with Heroku application and cell phone

I developed an app and deployed it on Heroku: You can find the project code here: https://github.com/AlexGioffre/Razeft However, when I try to open it on mobile, only the background appears and nothing else. Why is this happening? On a computer, everyth ...

Tips for merging arrays conditionally in JavaScript

Currently facing a dilemma without a clear solution, aiming to provide minimal context and focus solely on the problem at hand A worker logs their daily hours at work, stored in the "dayli_data" array. If the worker misses logging hours, it triggers the " ...

Tips on utilizing a local file as a background image URL

How can I modify my CSS to link to a local file path like C:\xampp\htdocs\Folder instead of the URL https://source.unsplash.com/1600x1050/?nature. I am currently using Bootstrap 4 and below is my CSS code: .jumbotron{ background: ...

Issues with Angular.js controller functionality

I am currently in the process of learning Angular and have been following the Intro to Angular videos provided on the official Angular website. However, I seem to be encountering an issue with my code that I can't quite figure out. The error message I ...

Having trouble with my React Navbar after integrating react-anchor-link-smooth-scroll

Code snippet for navbar.jsx: import React, { useState } from 'react'; import './Navbar.css'; import logo from '../../assets/logo.svg'; import underline from '../../assets/nav_underline.svg'; import { AnchorLink } fro ...

JavaScript code: Determine if a set of x/y points represents a circular shape

I have a matrix in the format below. I am looking for help to identify the outline that forms a circle: EDIT 1: What about the outline? The outline should not include spaces (each y-value should have at least 2 x-values). EDIT 2: What is considered a cir ...

Exploring the capabilities of VueJs in detecting events triggered by parent components

When users click on a specific image in the Collection(parent component), my goal is to display that image in a Modal(child component). Below is the code snippet: routes.js import Home from './components/Home'; import About from './compone ...

JavaScript code may fail to load on initial page load

My JavaScript function utilizes ajax and is triggered when a button is clicked. Oddly, the function works perfectly if you visit the page for a second time, but fails to work on the first visit. I've attempted to include window.onload, document.onlo ...

The functionality of the click event attached with the addEventListener is

I have a unique project where I am developing a user interface for a paper-rock-scissor game. To create the UI, I included four buttons: "Start game," "rock," "paper," and "scissor." Initially, I wrote separate code for each button, which worked perfectly ...

Minimize ring size through mesmerizing smoke effects

I came across this stunning ring with a captivating smoke animation, but I am struggling to comprehend its design fully. My goal is to resize the ring to about 80px and maintain only a single color throughout. However, my attempts to simply reduce the siz ...

Whenever the page is refreshed, the props in my application are dynamically updated thanks to the getStaticProps function I utilize

Currently, I am in the process of learning nextjs as a beginner. Through the utilization of the getStaticProps function, I have come to understand that data fetching occurs only once at build time and the values remain static thereafter. Despite this, I ...

What are the conditions for Jasmine's .toHaveBeenCalledWith to match the parameters?

I'm working on an Angular service along with its Jasmine test. The test is calling f1() and spying on f2(). The function f2 takes a variable v2 and updates it by setting field 'a' to 3. I expected the function f2 to be called with v2 (as def ...

Generating a JSON object based on the selection of dynamic checkboxes

Hello everyone, I am new to jQuery so please be patient with me as I embark on this journey! My goal is to structure my data in the following format... { "qualifications": [ "1", "7" ], units: [ "7", "3", "1" ] } The HTML looks like ...

How can I transform an HTML element into a textarea using CSS or JavaScript?

While browsing a webpage, I discovered a <div> element with the class .plainMail and I want to find a way to easily select all its text by simply pressing Ctrl+A. Currently using Firefox 22, I am considering converting the div.plainMail into a texta ...