Utilizing Props in TypeScript with React Styled Components

I created this styled component using TypeScript following the guidelines in their documentation

    import matrix from '../img/matrix.jpg';
    const Style = styled.div`
      .fixed {
        background-image: url(${props => props.image ? props.image : "../img/default.jpg"})
        z-index: -999!important;
        display: block;
        top: 0;
        left: 0;
      }
    `;
    export const FixedBackground = () => {return (
      <Style image={matrix}>
      </Style>
    )};

However, I encountered a compile error

Property 'image' does not exist on type 'ThemedStyledProps<Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, \"slot\" | \"style\" | \"title\" | ... 251 more ... | \"onTransitionEndCapture\"> & { ...; }, any>'

I attempted to modify the styled component like this

    const Style = (props: {image: string}) => {return (styled.div`
      .fixed {
        background-image: url(${props.image})
        z-index: -999!important;
        display: block;
        top: 0;
        left: 0;
      }
    `)};
    export const FixedBackground = () => {return (
      <Style image={matrix}>
      </Style>
    )};

Yet, I still faced a compile-time error

Type '{ children: never[]; image: string; }' is not assignable to type 'IntrinsicAttributes & { image: string; }'. Property 'children' does not exist on type 'IntrinsicAttributes & { image: string; }'."

Answer №1

Here is a suggestion for your code:

interface CustomStyle {
  imageURL?: string;
} 

const Custom = styled.div<CustomStyle>`
      .fixed {
        background-image: url(${props => props.imageURL ? props.imageURL : "../img/default.jpg"})
        z-index: -999!important;
        display: block;
        top: 0;
        left: 0;
      }
    `;

Answer №2

Upon reviewing the link provided, it appears that the image attribute is not being passed because you are using a basic div element. Since the image attribute is not recognized for the div element, it is not being passed along.

For more information, refer to the section titled "Passed props" and "Styling any component" for potential solutions.

Passed props: If the styled target is a simple element (e.g. styled.div), styled-components will transfer any known HTML attribute to the DOM. However, if it is a custom React component (e.g. styled(MyComponent)), styled-components will pass through all props.

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

Encountering errors while working with React props in typing

In my application, I am utilizing ANT Design and React with 2 components in the mix: //PARENT const Test = () => { const [state, setState] = useState([]); function onChange( pagination: TablePaginationConfig, filters: Record<string, ...

What is the best way to execute multiple functions simultaneously in Angular?

Within a form creation component, I have multiple functions that need to be executed simultaneously. Each function corresponds to a dropdown field option such as gender, countries, and interests which are all fetched from the server. Currently, I call th ...

What is the process for utilizing a user AD account with SecretClient in a node/TypeScript environment?

Currently, I am faced with authentication challenges while attempting to utilize the Azure Key Vault Secret client library (https://www.npmjs.com/package/@azure/keyvault-secrets). Most of the examples provided involve service principal usage, but my requ ...

Customizing a generic method in typescript

I am currently working on developing a base class called AbstractQuery, which will serve as a parent class to other classes that inherit from it. The goal is to override certain methods within the child classes. class AbstractQuery { public before< ...

Validating emails using angular material chips

I'm currently working on implementing a form that utilizes input chips to facilitate sending messages to multiple email addresses. While I've made progress in making the form functional, I'm facing difficulties in displaying error messages w ...

Exploring the nesting of client components in Next.jsIf you are

Exploring the realm of NextJS and React, I find myself delving into the realm of client components. One such client component I'm working with is called Form.jsx. It looks something like this: export default function FormHome() { ... a plethora of ...

Loop within a promise results in undefined

Within my application, there is a function that returns a promise. Inside this function, I wait for an image in the DOM to become available and then extract that element to generate base64 data from it. getCodesOfOneMerchant(merchantDataEntry: MerchantData ...

Restrict the scope of 'unknown' to an object containing only a string-field without resorting to 'any'

Currently, I am working on validating the data that is being received by my application. To illustrate, consider the following scenario: function extractField(data: unknown): string { if (typeof data !== 'object') { throw new Error(& ...

Error: The reference to "global" is undefined and was not caught in the promise

After successfully running my project, I encountered an issue upon installing the aws-sdk package from here. Despite trying to find solutions online, I have been unable to resolve this problem. The error message I am facing is: core.js:1673 ERROR Error ...

Tips for accurately defining the return type for querySelector(All) connections

I enjoy doing this particular task, ensuring the types are correct. const qs = document.querySelector.bind(document) as HTMLElementTagNameMap | null; const qsa = document.querySelectorAll.bind(document) as NodeListOf<any>; While hovering over query ...

defaultValue cannot be used with createContext

Currently, I am endeavoring to establish a context utilizing the createContext method from the react API: import React, { useState, createContext } from 'react'; export const MovieContext = createContext(); export const MovieProvider = (props) ...

TS2367: Given any input, this condition will consistently evaluate to 'false'

I'm struggling to understand why the compiler is not including null as a possible type for arg, or perhaps I am misinterpreting the error message. static vetStringNullable(arg:any): string|null { if (typeof arg === 'string') { ...

How about utilizing React's conditional rendering feature?

I'm currently working on a component that displays tournaments and matches, and I'm facing a challenge in implementing a filter option for users to select tournaments by 'league', while still displaying all tournaments if no 'leagu ...

Material-UI and TypeScript are having trouble finding a compatible overload for this function call

Currently, I'm in the process of converting a JavaScript component that utilizes Material-ui to TypeScript, and I've encountered an issue. Specifically, when rendering a tile-like image where the component prop was overridden along with an additi ...

Navigating to specific rows in a primeng virtualscroll table using the scrollToIndex

Utilizing Primeng virtual scroll table in Angular to manage large datasets in an array. I am interested in using the scrollToIndex. Is there an equivalent of cdk-virtual-scroll-viewport in Primeng table? I need the functionality where, upon a user clicking ...

Leveraging editor.action.insertSnippet from a different plugin

I am attempting to enhance the functionality of VS Code by adding buttons to the status bar that automatically insert code snippets. I am utilizing this Extension for this purpose. Additionally, I have configured keybindings in my keybindings.json file whi ...

React Query mutation encountered a TS2554 error: Type argument was not valid

I'm a beginner when it comes to TypeScript and I am using react-query. I tried using mutate, but it is causing an error. TS2554: Expected 1-2 arguments, but got 3. interface: interface ChangePassword{ email: string; password: string; conf ...

Tips for implementing collapsible functionality that activates only when a specific row is clicked

I need to update the functionality so that when I click on a row icon, only that specific row collapses and displays its data. Currently, when I click on any row in the table, it expands all rows to display their content. {data.map((dataRow ...

Creating TypeScript unit tests for nested functions: A step-by-step guide

I'm currently working with Angular 16 in combination with the ngRx framework. My development involves TypeScript coding and writing unit tests (.spec.ts) using Jasmine, especially for code similar to the example below. How do I invoke this method with ...

What is the method to access an interface or type alias that has not been explicitly exported in TypeScript type definitions?

I am looking to create a new class that inherits from Vinyl. The constructor in the superclass takes a single parameter of type ConstructorOptions. export default class MarkupVinylFile extends Vinyl { public constructor(options: ConstructorOptions) { ...