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

Elevate the appearance of your UI with stylish Material text

I'm struggling to customize a material-ui textfield to achieve my desired look. I simply want a clean and plain white input field with the standard MUI animations. It's important that the textfield always has a white background and the text appea ...

How can I activate a disabled option number 2 after selecting option number 1?

I have encountered an issue with my JavaScript code. The second "select" element is supposed to be disabled by default, but I want it to become enabled when an option is selected from the first "select". However, this functionality is not working as expect ...

How can I update the parent's state in React based on the child's state?

Just starting out with React. I'm facing an issue where I need to update the state of a parent component from a child, even though I've passed a callback function successfully to the child component, it's not working as expected. My main c ...

How to Style a Diamond Shape with Content Inside Using CSS

Can someone help me figure out how to create a diamond-shaped background in HTML? I want the diamond shape to contain text and images, similar to what's shown in this screenshot. The example image uses a background image of a diamond, but I'm loo ...

Attempting to apply two different animations to a single element

Trying to implement two different animations, with one triggering before the other. In the Codepen and snippet below, you can observe that the initial animation rearranges the icons to their original positions upon page load. The second animation involves ...

Creating a step wizard form with ReactJs can be accomplished by breaking down the form into

I have developed a resume generation application with two main components: BasicDetails and EmploymentDetails. To see a working example, click here: https://codesandbox.io/s/next-dynamic-testing-issue-forked-h1nt8 index.js file: <form onSubmit={ha ...

Retrieving an array of various responses using Axios

My current code includes a function that retrieves exchange rates for various stocks: export const getRates = (symbole1, symbole2, symbole3) => { const res = [] axios.all([ axios.get(`${baseUrl}/${symbole1}`), axios.get(`${ ...

The iPhone header position switches when an HTML5 input type number is selected

I am currently working on a project that involves jQuery Mobile and PhoneGap. One issue I am encountering is when using the iPhone version, the header position changes when I click on an input type number. NOTE: When I focus on the input type number in my ...

I am unable to employ filtering in TypeScript

Hey there, I'm trying to filter some JSON data randomly by using this function, but I keep running into an error with my variable called filteredArray. The error message says "Property 'filter' does not exist on type 'Dispatch<SetSta ...

What could be causing the background color not to change on the HTML page with Bootstrap?

Learning html, bootstrap, and css styling can be a confusing endeavor. Sometimes things don't work as expected, like changing the background color. Despite following what seems like a simple solution after googling, the background color remains unchan ...

When encountering error code EINTEGRITY during npm installation, a warning about a potentially corrupted tarball may be displayed

I have been facing an issue for the last three days with my react+vite project on Windows 10. Whenever I attempt to install dependencies using npm install, I encounter the following error: npm WARN tarball tarball data for fast-levenshtein@https://registry ...

The compatibility of MUI installation with React 16 is currently not functioning

My React version is 16.1.3 and I am encountering difficulties trying to install the following two packages: @mui/material @mui/x-data-grid I have attempted to install all versions, from the lowest to the highest, but unfortunately none seem to work. In m ...

Refresh data with Axios using the PUT method

I have a query regarding the use of the HTTP PUT method with Axios. I am developing a task scheduling application using React, Express, and MySQL. My goal is to implement the functionality to update task data. Currently, my project displays a modal window ...

Is there a way to refresh the ScriptTagger.js file in React after updating the DOM?

How do I use the script from the website file located at ? In the Website / Non-Wordpress Blog Installation section, I have successfully added the script to index.html and the header, but it seems to only work with existing elements on the page. For inst ...

What is the best way to arrange multiple Material UI select components in alignment?

I am encountering an issue with aligning multiple Material UI select components within my application. As depicted in the image, you can observe that the components are not properly aligned. How can I apply consistent styling to these components so they ...

incorporating event handlers to references retrieved from bespoke hooks

I have designed a simple custom hook in my React application to manage the onChange events of a specific input element. const useInput = () => { const ref = useRef(null); const handleChange = () => { console.log("Input has been ...

"React - encountering issues with state being undefined when passing child state up through parent components

I am currently navigating the world of react and have encountered a hurdle. I find myself facing difficulties in updating the parent component based on changes in the child state. I was able to pass the child state to the parent by linking the child's ...

Automatically refresh the interface elements in ReactJS

I am new to React and unsure if this question should be asked. After searching through numerous blogs, I am still unable to come to a conclusion. I have a continuously updating REST API on the server side, such as a stock data API for example. My issue a ...

How to stop crosshair line at the intersection point of x and y axes on a line graph using Highcharts

I feel like using an image would help better illustrate my question. https://i.stack.imgur.com/LJN12.png Whenever I enable crosshairs, they extend from the bottom of the chart to the top. Is there a way to create a crosshair that only intersects at the x ...

Combine internationalization JSON files with Webpack

I'm currently working on a project using React and implementing multilingual support with i18next. Each component has its own folder named locale, containing multiple json files for each language. To streamline the process, I want to combine all thes ...