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

Remove the boundaries from the grid and only retain the box

I am not skilled in css, but I simply want to eliminate the interior edges of the box and retain only the outer edges. .grid-container { display: grid; grid-template-columns: auto auto auto; background-color: #2196F3; padding: 10px; } .grid-ite ...

Why does the devServer port ignore the loading of webpack chunks?

I'm attempting to implement dynamic imports using React.lazy. The code is fairly straightforward: import React, { Component, Suspense, lazy } from 'react'; const LazyComponent = lazy(() => { return import('./lazy'); }); c ...

Error TS[2339]: Property does not exist on type '() => Promise<(Document<unknown, {}, IUser> & Omit<IUser & { _id: ObjectId; }, never>) | null>'

After defining the user schema, I have encountered an issue with TypeScript. The error message Property 'comparePassword' does not exist on type '() => Promise<(Document<unknown, {}, IUser> & Omit<IUser & { _id: Object ...

Creating a File Download button in Next.js without receiving a "window is not defined" error

React components don't recognize 'window' or 'document' objects until the component is mounted. I'm working on creating a download button that will receive an Excel file processed by the backend server. In my previous non-Rea ...

What is the best way to transfer information from a React front end to a Node Express backend?

I recently finished developing an application and I needed a way to transmit data from my OnSubmit function to the express backend for storage. Below is the server-side code: const express = require('express'); const bodyParser = require('b ...

Changes in React BrowserRouter URLs are not reflected on the page or components, requiring a manual refresh for them to

Greetings, fellow developers! I have developed an app using React with a remote menu component. Despite trying numerous techniques, I am facing an issue where my URL changes but the components are not rendering on the screen. You can check out the code h ...

The label text boldly stands out against the MUI outlined input

When I use an MUI outlined input, it appears as shown below: where the text "New Password" is struck through This is the code I am using, can anyone help me with this. <FormControl fullWidth variant='outlined'> <InputLabel htmlFor=& ...

Is it possible to prevent a webpage from being refreshed?

I need help with an HTML page that puts the worker on pause time which will be subtracted from his/her day job. The issue is that when he/she refreshes the page, the timer starts from the beginning automatically. I want it to continue without resetting. Is ...

What causes *ngIf to display blank boxes and what is the solution to resolve this problem?

I am currently working on an HTML project where I need to display objects from an array using Angular. My goal is to only show the objects in the array that are not empty. While I have managed to hide the content of empty objects, the boxes holding this co ...

Angular's browser animation feature allows for smooth slide-up animations from the bottom

I have been experimenting with creating a simple animation, and it's working, but in the opposite direction of what I intended. I want the div to open from bottom to top and close from top to bottom. Here is my animation code in Angular: animations: ...

What is the best way to integrate @uirouter in the Angular/sampleapp project?

Having trouble configuring the angular/sampleapp to work with @uirouter. Is the systemjs.config.js file set up incorrectly to include @uirouter? 1) Run npm i -S @uirouter/angular 2) Add the following line to the map section in systemjs.config.js ' ...

Incorporating invisible surprises into a fixed menu that reveal themselves as you scroll

I am working on implementing a top navigation and a sticky sub-navigation feature. The goal is to have the sticky nav become the top nav when the user scrolls down the page, similar to the functionality on this website - The issue I'm facing is with ...

Scroll horizontally within each row

I am attempting to create a table with individual horizontal scrolling for each row, dynamically. Currently, my code only allows the entire table to scroll horizontally, not the individual rows. <table class="table-mainprojects"> <tr> < ...

Can anyone suggest a more efficient method for validating checkbox selection in Angular?

I am working with an angular material stepper, where I need to validate user selections at each step before allowing them to proceed. The first step displays a list of 'deliveries' for the user to choose from, and I want to ensure that at least o ...

Utilizing TypeScript with Context API

This is my first time working with Typescript to create a context, and I'm struggling to get it functioning properly. Whenever I try to define interfaces and include them in my value prop, I encounter errors that I can't figure out on my own. Spe ...

"Troubleshoot: Why is the Position Absolute Not Functioning in

Trying to achieve a layout similar to the last element at the bottom of the footer] 1, but getting something like this instead: <footer> <div class="container-fluid"> <div class="row"> <div class="col-m ...

Storing an image in MongoDB using Multer as a file from Angular is not working as anticipated

I'm currently dealing with an issue that I believe is not functioning correctly. I installed a library in Angular called cropper.js from https://github.com/matheusdavidson/angular-cropperjs. The frontend code provided by the developer utilizes this li ...

"Explore the functionalities of Drupal's innovative Menu module: How sub-sub menus can take precedence over sub-menus

When visiting , I noticed that the Nice Menu module for Drupal is not displaying sub-sub menus properly. If you navigate to the first item in the menu and then select the first one in the sub-menu (Facilities->Spring->Calendar), you'll see that the Ca ...

Conceal a Column within the Material UI Data Grid

I have managed to hide the id on the columns but it is still visible in the filter. Is there a way to also hide it from there? CLICK HERE const userColumns = [ { field: "id", hide: true }, { field: "name", headerNa ...

The HTML dropdown menu is malfunctioning

I've been struggling to create a website with a dropdown menu. Despite following various guides and searching for solutions, the menu is behaving strangely. I've tried numerous tactics, so some lines of code may be unnecessary. The submenu is ap ...