Troubleshooting: Inline Styles not displaying Background Div Images in Next.Js

I am currently attempting to display images in a component by using a map and an external JS file to store the images as objects. I then loop through them to set each one as a background image for every created div. However, it seems like my current implementation is not working as none of the images are showing up.

Component File: WorkImages.js

export default function WorkImage({workImages}) {
    return (
        <div>
            {
                workImages.map((work) => {
                    return (
                        <div style={{backgroundImage: `url(${work.image})` }} id='work-img' className='work-img' key={work.id}>
                                <a href=""><div className="overlay">View Work</div></a>
                        </div>
                    );
                })
            }
        </div>
    )
}

Object File Where I am Retrieving the images from when looping (image.js):

import img1 from '../public/images/filler1.jpg'
import img2 from '../public/images/filler2.jpg'
import img3 from '../public/images/filler3.jpg'

const image = [
    {
        id: 1,
        image: img1
    },
    {
        id: 2,
        image: img2
    },
    {
        id: 3,
        image: img3
    }
]

export default image;

Main File Where I am trying to render out the divs with the dynamic background images (Work.js): import Aos from 'aos' import 'aos/dist/aos.css'

import {useEffect, useState} from 'react'
import WorkImage from './WorkImage';
import image from './image'

export default function Work() {
    const [workImages, setImage] = useState(image);
    useEffect(() => {
        Aos.init({duration: 2000});
    }, []); 
    return (
        <section id='work' className='work-section'>
            <div data-aos='fade-left'>
                <h1 className="work-header">- RECENT WORK -</h1>
                <div className="showcase-wrapper">
                    <WorkImage workImages={workImages} />
                </div>
            </div>
        </section>
    )
}

Answer №1

Update your images array to include:

const images = [
    {
        id: 1,
        image: '/images/filler1.jpg'
    },
    {
        id: 2,
        image: '/images/filler2.jpg'
    },
    {
        id: 3,
        image: '/images/filler3.jpg'
    }
]

export default images;

If the images are already in the public directory, there is no need to import them.

Check out: Static File Serving


For those encountering a similar issue without using the public directory:

When using

import img from 'path/to/img.ext'
, img is of type StaticImageData, defined as:

type StaticImageData = {
  src: string;
  height: number;
  width: number;
  placeholder?: string;
};

In such cases, utilize img.src for the URL. You can also use this alternative approach instead of the previous solution:

{backgroundImage: `url(${work.image.src})` }

In this specific scenario, you could simplify by not needing an images object since the files are correctly named sequentially. The following approach should also suffice:

Array.from({ length: 3 }, (_, i) => i + 1).map((i) => (
  <div
    style={{ backgroundImage: `url(/images/filler${i}.jpg)` }}
    id={`work-img-${i}`}
    className='work-img'
    key={`work-${i}`}
  >
    <a href='/'>
      <div className='overlay'>View Work</div>
    </a>
  </div>
));

PS: Adjust your id and key in map. Setting the same id for multiple elements and utilizing index as key is not recommended.

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

Discover the best way to enable lint support for MUI `sx` prop values

Despite attempting the method below, I am still unable to receive lint support to identify incorrect style properties and values. import { SxProps, Theme } from "@mui/material"; export const navBarStyles: Record<string, SxProps<Theme> | ...

What is the best way to connect a fresh post to a different URL in ReactJS and Redux?

Currently, I am working with Redux and ReactJS to develop a discussion platform. One of the key features I am trying to implement is where users can input the title and content of their post, which will then be submitted to create a new post. After submit ...

Urgent concern: the require function is being utilized in a manner that prevents the static extraction of dependencies [mysterious]

After implementing the magic-sdk version 8.0.1 on my project, I encountered the following warning message: warn - ./node_modules/magic-sdk/dist/es/index.js Critical dependency: require function is used in a way in which dependencies cannot be statically e ...

The process involves transferring information from a specific div element to a database. This particular div element obtains its data after receiving an appended ID

It's a bit complicated, but I'm working on creating a tag system. I'm fetching data from a database with an AJAX call using the "@" symbol. Everything is working fine - the tags are being generated, but I'm having trouble retrieving and ...

Encountering a fatal error in the Next.js application: "Mark-compacts near heap limit allocation failed issue is hindering the smooth

When I'm working in Next.js, I often encounter the issue of not being able to run my project after work. https://i.stack.imgur.com/IA5w3.png ...

Pick out grouped objects without the use of Javascript

I am looking to design a single page where the display of categorized items changes based on user selection. Ideally, I want this to be chapter/hash (:target) dependent, but checkboxes influencing state would also work. As an experiment, I am trying to ac ...

Encountering a build error with private identifiers while implementing the openai 4.0 package in next.js version 13

After incorporating the new 4.0 openai package into my next.js app, I encountered an error during the build process when using it solely on the server side. - info Linting and checking validity of types .Failed to compile. ./node_modules/openai/src/core.t ...

Inserting a singular image following a designated list item

I have a question that may seem silly, but I'm trying to understand a specific CSS styling issue. I want to add an image targeting a particular li item. Currently, the code adds the image after all the li items: .menuStyling li:after{ content: u ...

Input a new value into the registration field to update it

My current task involves adding a new text field to a React form using a button. I need this new input text field to be able to store data on a register. How can I go about setting this property? Typically, when creating a text field, you would utilize co ...

Issue with ESLint arises following the installation of npm create-react-app package

ESLint is showing Invalid Options: - Unknown options: env, parserOptions, rules. The 'parserOptions' has been removed and you should now use the 'overrideConfig.parserOptions' option instead. Similarly, the 'rules' have been r ...

Text input fields failing to record text

I've set up a forum using react-redux and material ui, but I'm facing an issue where the text fields are not updating based on state changes. When users try to type in the text field, nothing seems to happen. onChange={e => onT ...

What can be done to stop Bootstrap columns from shifting positions or stacking on top of each other unexpectedly?

I'm currently working on a testimonial section for my project. The challenge I'm facing is that the content within the 4 divs is not evenly distributed. As a result, when I try to adjust the width of the screen and expect them to align in a 2-2 f ...

Overlap and cover additional elements within a DIV

I am looking to create a versatile function that can effortlessly overlay various elements such as selects, textfields, inputs, divs, tables, and more with a partially transparent div matching their exact height and width. I have managed to obtain the pos ...

Having trouble getting a React app integrated with WordPress on an NGINX server to function properly over HTTPS?

I am currently in the process of developing a React application that integrates with a WordPress site. The setup I am aiming for is as follows: When users visit example.com, they will be directed to my React app. If they navigate to example.com/blog, they ...

overlaying an image with a CSS box and then dynamically removing it using JavaScript

I am new to JavaScript, so please bear with me if this question seems quite simple. I am facing an issue with my current task. There is an image on a web page. My goal is to place a black box on top of the image (using CSS) to cover it up. Then, with th ...

Simplest method for integrating Grid system using Material-UI

Feeling a bit lost in the extensive world of React App ecosystems, I'm seeking the simplest yet effective solution for implementing a grid system using Material-UI. Can someone point me towards the best option and provide a brief explanation on how t ...

Display CPU consumption using React JS

Can the current CPU usage be displayed on screen in a React-JS application? I have come across node.js examples but none specifically for React. Node example packages: https://github.com/oscmejia/os-utils ...

What is the best location for storing test utilities in Next.js applications?

My Next.js (12.x) React (18.x) project includes Jest (28.x) for testing. While my tests in files like __tests__/Product.test.tsx work smoothly, I encountered an issue when trying to reuse some utils across tests: __tests__/util/my-test-helper.ts export fu ...

Nested functions in React.js

Can React.js utilize packages or services like this? I want to implement the following function as a package/service that can be called in every React.js component. How can I achieve this? let tokenService = { setToken: (token, e ...

Ways to determine the current page I am viewing

I am working with a list of tabs and I need to track my current location every time I click on a specific tab. My MainCTRL controller, which is the parent of all tab controllers, needs to be aware of the active tab at any given moment. I attempted to use n ...