Setting the path to an image component using the style jsx tag in Next.js: A step-by-step guide

While utilizing jsx to define styles for my NextJs components, I am facing the challenge of defining a background image for certain elements.

I have realized that only relative paths or absolute paths are accepted. But how can I pass a relative path to the component itself?

Below is a simple component function I have created for testing purposes:

import React from 'react'

const  TestComponent = (props) => {
    return (
        <div>
        <h1 className="test">See my background</h1>
        <style jsx>{`
        .test {
            background-image: url("someImageFile.jpg");
        }
        `}</style>
        </div>
    )
}
export default  TestComponent

However, this setup triggers a 404 error with the URL "localhost:3000/current page/someImageFile.jpg".

Answer №1

When creating a NextJS application, it's essential to have a dedicated public folder in the root directory of your project. This folder is where you should store all your static files, such as images.

If you're looking for detailed instructions on how to set up this folder correctly, check out the official documentation provided by NextJS:

https://nextjs.org/docs/basic-features/static-file-serving

Answer №2

To efficiently utilize the $ symbol for invoking the require function, follow this method:

<style jsx>{`
      .test{
        background-image: url(${require("./someOtherImageFile.jpg")});
      }         
`}</style>

For more information, check out the official documentation.

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

The onKeyUp function seems to be malfunctioning in React-Select

I am looking to capture the character whenever there is a change in the text from a multi-select dropdown menu. Unfortunately, the onKeyUp event is not triggering as expected. Here's the code snippet for your reference: const options = [ { label ...

Adjusting the color settings in Tailwind within the Next.js project resulted in a malfunction with all color

Recently delving into the world of TailwindCSS within a Next.js project, I eagerly followed their recommended approach for integrating with Nextjs. However, my attempt to enhance the color options in the tailwind.config.js file unfortunately resulted in al ...

css - targeting the last child element using a type selector

I'm attempting to target the final child element of type <div> within the container "#myDiv" <div id="myDiv"> <div> <img> <div> <div>text</div> ...

Is it possible to utilize nth-child() without recursion?

Can the CSS selector parent child:nth-child() be used to target only children? The HTML code is as follows: <body> <div>div 1</div> <div> div 2 <div>div 2.1</div> <div>div 2.2</ ...

Tips for ensuring that a nested object in an array contains only a single object

My array is structured like this: [ { object1:{ childObj1:[grandChild1,grandChild2], childObj1, childObj1} }, { object2:{ childObj1:[grandChild1,grandChild2], childObj1, childObj1} }, { object3:{ childObj1:[grandChild1,grandChild2 ...

The interaction between jQuery Masonry and Bootstrap results in unexpected grid behavior

I've spent hours trying to solve this problem, but I can't seem to get it to work as intended. I want the layout of my boxes to be like this using Bootstrap grids: However, after implementing the jQuery Masonry plugin (which I used to manage va ...

Newcomers to Visual Studio Code facing a problem with images not displaying

As a beginner in all aspects, I am currently facing an issue with displaying an image on Visual Studio Code. The problem arose when I tried to create a separate folder for the image, which resulted in a cascade of subfolders that only made things worse eac ...

react-datepicker displaying error message "Preventing default action not possible within a passive event listener invocation"

I've integrated the react-datepicker library in portal mode. While it functions well on browsers, I encounter an error when using mobile browser mode. An issue arises stating: "Unable to preventDefault inside passive event listener invocation" Des ...

Guide: Making the Clear Button Function in MUI Date Picker

I am currently working on a React project where I have incorporated a MUI TextField of type='date' (Date Picker). However, I am facing an issue with the Clear button not functioning as expected. The intended behavior is for the Clear button to re ...

Challenge encountered in handling AJAX response data for presentation

Currently, I am immersed in a project and decided to implement AJAX for smoother form submissions. My initial attempt was trying to display text from a .txt file below the "submit" button, but unfortunately, that approach didn't yield the desired resu ...

Applying Compiled CSS file in Node.js using Express and SASS not working as expected

Recently, I've delved into utilizing NodeJS with Express to serve my pug files. In addition, I decided to incorporate the "express-sass-middleware" to compile and serve the scss/css files in my project. While everything seems to be functioning as expe ...

Move your cursor over an image within a div container

After not finding any helpful answers on this topic, I've decided to ask for help again. My issue involves having an image inside a div. <div id ="gratterlendis"> <a href ="?page_id=8"><img src="img/gratterlendis.png" align="right" wid ...

Tips for sending custom properties to Material-UI component via makeStyles/withStyles

Is there a way to pass custom props to an MUI component? For example, if I want to set the background color of a component using customProps='red', how can I achieve this? I specifically need to change the background color of a button, and I was ...

Is it possible, (and recommended), to determine the HTML elements that a component renders by utilizing Enzyme's shallow() method?

The query: I'm currently developing a unit test for a React component named <BaseEdit />. To ensure that the component is functioning properly, I aim to verify that it will display an HTML element <input/>, and I intend to achieve this us ...

Can anyone explain to me why the data I'm passing as props to the React functional component is displaying as undefined?

I have encountered an issue with a pre-made React component where I am unable to see the data being passed as props when I console log it. I am unsure if I am passing the prop correctly, as I have used the same prop successfully in other class-based comp ...

It seems that Firefox is ignoring the word-wrap style when the class of a child element is changed

Take a look at this: var iconIndex = 0; var icons = ['check', 'chain-broken', 'flag-o', 'ban', 'bell-o']; $('button:eq(0)').click(function() { iconIndex = (iconIndex + 1) % icons ...

Gatsby causing issues with Material UI v5 server side rendering CSS arrangement

I shared my problem on this GitHub issue too: https://github.com/mui-org/material-ui/issues/25312 Currently, I'm working with the Gatsby example provided in Material UI v5: https://github.com/mui-org/material-ui/tree/next/examples/gatsby After imple ...

Why is it unnecessary to include a callback when using a setState function from useState as an argument in useEffect?

While working with a function from my component in the useEffect arguments, it is recommended to write a callBack so that it is memorized and used as a dependency of the useEffect. Without this, there is a warning. However, when using the setState of use ...

Using useRef as a prop in React with TypeScript

I am currently experimenting with TypeScript and encountering an issue when trying to use useRef in a custom element specifically when passing it as a prop I have attempted the following: import React from "react"; export interface InputProps extends ...

A webpage styled with w3.css featuring text without any underline

I am currently using w3.css but I'm facing an issue where some of my hyperlinks have underlines while others do not. My goal is to remove all underlines from the hyperlinks in the content below: <ul class="w3-ul w3-white"> <a class="" href=" ...