Issue resolved: Mysterious fix found for background images not displaying in NextJS React components

I am having trouble displaying a background image on an element in NextJs using Typescript and Tailwind. I do not believe it is a TypeScript issue since I am not receiving any errors or IntelliSense warnings. Below is the code I am working with:

var classnames = require('classnames')
import Image from 'next/image'

interface LandingPageSection
{
  imagedata: imagedata,
  children?: React.ReactNode
}

interface imagedata
{
  src: string,
  width: number,
  height: number,
  alt: string
}

export default function Section({ imagedata }: LandingPageSection)
{
// var styleatt={backgroundImage: `url(${imagedata.src})`}


  return (

<div className={classnames("shadow bg-white border border-black")}>
    <div className={classnames(`bg-size bg-cover bg-center`)} style={{backgroundImage: `url(${imagedata.src})`}}>
      <Image src={imagedata.src} width={150} height={150} alt={imagedata.alt}>
      </Image>

        <div className={classnames("p-4 h-32 flex items-end text-black")}>
            <h3 className={classnames("mb-2")}>Card Title</h3>
        </div>
    </div>
    <div className={classnames("p-4")}>
        <p className={classnames("text-grey-600 text-sm)")}>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo
            ligula eget dolor.
            Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus
            mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. </p>
        <div className={classnames("mt-4")}>
            <a href="#" className={classnames("no-underline mr-4 text-blue-500 hover:text-blue-400")}>Link 1</a>
        </div>
    </div>
</div>
  )

According to Chrome dev tools, when hovering over the element, there is an 'invalid property value' error related to the background-image styling.

Why is this happening and how can I rectify it? Some suggest that importing the image at the beginning might solve the issue, but I am unsure why that would be necessary, especially considering the need for dynamic images based on props.

I came across a Tailwind template on this site that I wish to customize for Next and TypeScript. Background images will likely be required as the project progresses.

I acknowledge that inline styles are useful for succinctly describing specific styling needs, yet many resources within the react community advocate for avoiding inline styling in JSX/TSX files. Using classes, frameworks, or external stylesheets is preferred, although I recognize the challenge of dynamically passing image paths through these methods. This lack of flexibility may necessitate resorting to inline styles to accommodate such dynamic requirements. The scarcity of documentation on this topic adds to my curiosity regarding the rendering issues observed.

Thank you!

EDIT:

The issue was due to whitespaces. Credit goes to aegatlin for pointing this out.

However, despite passing a string as shown below where the syntax successfully loads the icon image, something appears different either due to inline styling or prop passing. Although the solution is simple by renaming folders without spaces.

import Head from 'next/head'
import Infobar from '../components/Infobar'
import Section from '../components/Section'
import styles from '../styles/LandingPage.module.scss'
var classnames = require('classnames')

export default function LandingPage()
{
  return (
    <div className={styles.container}>
      <Head>
        <title> Acme Widgets| FREE TRIAL</title>
        <link rel="icon" href="/images/Landing page images/Logo/Logo_D logo.png" />
      </Head>
      <main className={classnames(`${styles.w99}`)}>
        <Infobar>
        </Infobar>

        {/* top banner */}
        <Section imagedata={{src:"/images/Landing page images/Top_banner/Top_banner_face_leaves14690559.jpeg", height:50, width:50, alt:"woman's face"}}> 
        </Section>

        {/* second banner */}
        <Section imagedata={{src:"/images/Landing page images/Second_banner/cerreal2_large_1545151190.png", height:50, width:50, alt:"bowl of cereal with fruit"}}> 
        </Section>

        {/* etc */}

      </main>

    </div>
  )
}

This is where the string is passed from. Indeed, they were correct - there are

Answer №1

It seems like the value of your imagedata.src string is not valid. Can you share an example string for reference?

The src value should be a proper URL pointing to a static file that can be accessed from either your server or online.

If the string you provided in your question with the strikethrough text contains spaces in the file path, it will not be considered a valid URL.

Additionally, when working with NextJS, ensure that you are serving static files such as images from the /public directory.

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 it possible to implement the ::selection Selector in Material-UI?

Is it possible to change the background color of a selected list component in Material-UI using the ::selection selector? See the code example below: import React from 'react'; import { makeStyles } from '@material-ui/core'; import List ...

Leverage the keyof operator for automatic determination of return type

My interface looks like this: interface ResourceState<ItemType> { rows: ItemType[], store: Record<String, ItemType> } To create a root state, I use the following structure: RootState{ car: ResourceState<Car> user: ResourceState<User&g ...

Tips for concealing a "PARTICULAR TAB BAR ITEM" on a bottom tab bar in @react-navigation/bottom-tabs

Check out this video displaying my current visible bottom tab items: Home, My Account, Cart, and Menu. Watch here I have additional bottom tab items like SettingsView that I want to render on the screen but keep them hidden from the bottom tab bar itself. ...

Unusual Interactions between Angular and X3D Technologies

There is an unusual behavior in the x3d element inserted into an Angular (version 4) component that I have observed. The structure of my Angular project is as follows: x3d_and_angular/ app/ home/ home.component.css hom ...

Utilizing Angular 2 for Element Selection and Event Handling

function onLoaded() { var firstColumnBody = document.querySelector(".fix-column > .tbody"), restColumnsBody = document.querySelector(".rest-columns > .tbody"), restColumnsHead = document.querySelector(".rest-columns > .thead"); res ...

Having trouble updating the value of my textfield in material-ui using formik

Below is the code I'm working with to set a default value using the material-ui Textfield API within a formik fieldarray: <TextField name={`myGroups.${index}.myGroupName`} value={`Group ${index+1}`} label="Group" InputProps={{ ...

incorrect sequence of div elements appearing vertically

I'm having trouble organizing the header, page title, and navigation bar on my webpage. Despite my attempts to structure them correctly, they are not displaying in the desired order as shown below: https://i.stack.imgur.com/A3rQe.jpg The issue arises ...

Cannot Display CSS Background Image Locally

Apologies for the simple inquiry, but I am facing an issue with displaying my background image using background-image:url() in the CSS. Strangely, it does not work with this method, but when I use content:url(); it works just fine. Interestingly, backgrou ...

Tips on extracting a value from a subscription

I am trying to figure out how to pass a value from a subscribe function to a variable so that I can manipulate it later on. For example: getNumber: number; I need to be able to access and use the variable getNumber in the same .ts file. someMethodT ...

Issue: Incorrectly calling a hook. Hooks can only be used within the body of a function component. Assistance needed to resolve this issue

import React, { useState } from "react"; const RegistrationForm = () => { const [name, setName] = useState(""); const [password, setPassword] = useState(""); const [email, setEmail] = useState(" ...

What sets id and class apart from each other?

I understand that for id we need to use the '#' symbol and for class '.' symbol. However, I am unsure of the specific purposes of both class and id in styling CSS. Can someone provide clarification on when I should use id and when I sho ...

What is the proper way to provide parameters for express.use to avoid encountering a type error?

When attempting to use the path string in this code snippet within the function, an error is thrown. The argument type string cannot be assigned to the parameter type RequestHandler<RouteParameters>    The assigned type does not contain call si ...

5 horizontal navbar with dropdown menu in Bootstrap

I am currently utilizing bootstrap 5. Is it possible to display my navbar menus horizontally like the image provided? show submenus horizontally as shown in this picture I would also like to implement submenu for other submenus up to 4 levels deep. Any ...

What is the best way to shade the background when a hyperlink is pressed?

I am currently working on customizing the navigation bar for my website. My navbar consists of five elements, and I want to make an element appear darker when it is clicked. Here's what I have attempted so far: Utilizing jQuery to modify the ac ...

What is the best way to utilize the bootstrap grid system for smaller screens while incorporating a table?

I have a PHP generated table that retrieves data and dynamically displays it in a table. It is crucial to ensure that the table data adjusts according to the screen size. Below is the code snippet: echo "<div class='container'><div cla ...

Retrieve the essential information needed from the REST API

I have a test wordpress blog set up. To enhance the functionality, I developed an angular app that utilizes the wordpress rest api. The app makes a call to an endpoint to retrieve categories. However, the JSON response contains unnecessary data for my appl ...

CSS Only Sidebar Dropdown (without using Bootstrap)

I want to create a sidebar with collapsible dropdown options and smooth animations using only pure css/js/html/jquery, without relying on bootstrap like I did in the past. Here is an example of what I created previously with bootstrap: Now, as a challenge ...

typescriptIs there a more efficient approach to typing optional values without a default value in

In my React application with TypeScript, I am using the following code to provide typed props: type ScheduleBoxContentProps = { desc: ReactNode, lottie: LottieProps, } & Partial<{className: string}>; I want the className prop to be optional ...

After updating the node modules, the styling of MUI Styled components disappeared

Our frontend framework of choice is @mui. Things were running smoothly for quite some time until a recent issue arose. Following the deletion and reinstallation of node_modules, our components seemed to have lost their styling. Upon closer inspection duri ...

Tips for sorting queries within a collection view in Mongoose:

I am working with Mongoose and creating a view on a collection. NewSchema.createCollection({ viewOn: originalModel.collection.collectionName, pipeline: [ { $project: keep.reduce((a, v) => ({ ...a, [v]: 1 }), {}), }, ], ...