Incorporating a background image into a Material UI theme with CSS styling

When customizing a theme in material UI, one can adjust or override it using the function createMuiTheme. Below is the complete file where this process is carried out:

import { createMuiTheme } from '@material-ui/core/styles';
import purple from '@material-ui/core/colors/purple';
import green from '@material-ui/core/colors/green';

//import wood from './static/wood.png';

const theme = createMuiTheme({
  palette: {
    primary: {
      main: purple[500],
    },
    secondary: {
      main: green[500],
    },
  },
  overrides: {
    MuiCssBaseline: {
      '@global': {
        body: {
          border: '2px solid blue',
          backgroundImage: 'url("/static/wood.png")',
        },
      },
    },
  },
});

export default theme;

The styling applied globally to the body, like the blue border, works fine. However, I am encountering difficulties with the background image.

Typically, by uncommenting the import statement at the top and adjusting the CSS line as follows:

backgroundImage: `url(${wood}),`

I face an error due to the import statement alone:

TypeError: Object(...) is not a function. It seems that there is something special about customizing a material ui theme that doesn't allow static assets to be imported in the same file.

Using a url for the image (as shown above) always results in a 404 error. Despite placing the image in src > static > wood.png, I receive:

http://localhost:3000/static/wood.png 404 (not found).

Despite trying numerous path variations, none have been successful. Research suggests that I am already using the correct path.

Is it only feasible to add a background image when it is hosted on a different server while customizing a Material UI theme?

All operational examples I discovered follow this approach (such as this one: https://codesandbox.io/s/v30yq681ql), but there must be a method to utilize locally stored images.

If the issue lies with my incorrect relative path, how can I identify the accurate path?

If there exists a more effective way to incorporate a background image into a page with Material UI, I am open to exploring alternatives, although currently, global body tag override seems to be the sole option.

Answer №1

If you move your image to the src directory instead of keeping it in the static folder, for example:

src/components/wood.png

Update your import statement to:

import wood from './components/wood.png';

Then set the backgroundImage property to:

backgroundImage: `url(${wood})`,

This should resolve the issue. I have used the same setup (with a different file name but in the same location) successfully.

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

Tips for resolving the issue with "Text Animation"

Could someone please help with fixing this CSS animation? I want to align the text animation to the paragraph properly. I'm not confident if I am approaching this in the correct way, so if there is a simpler solution out there, I would appreciate lea ...

Problem with CSS multi-level dropdown navigation in a vertical layout

I am in the process of creating a navigation menu with dropdown menus, which are working correctly. Now, I would like to add another sub-menu drop down inside dropdown 1, but I am having trouble getting it to function properly. How can I make Sub Menu 1 ac ...

Is there a way to designate whether the <ul> element is displayed horizontally or vertically?

For example: <ul> <li>a</li> <li>b</li> </ul> The default output is: ab But I am looking for: a b Is there a way to achieve this? ...

Triggering scroll snapping in CSS based on a different user action than just scrolling

Take a look at this example: https://codesandbox.io/s/spring-wood-0bikbb?file=/src/styles.css Try this to recreate the issue: Click on the input at the top Scroll to the bottom, then click on an empty area Observe how the screen jumps back up to the top ...

Using React hooks to reset state in a reducer: step-by-step guide

event.js import React, { useEffect, useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { Link, useHistory } from 'react-router-dom'; import { addEvent } from '../actions/event'; ...

Can you explain the Runtime Environment for React applications and detail the request-response flow within a React application?

Having previously worked on Java based web applications and now transitioning to ReactJS applications, I have some questions that I hope you can help me with: I understand that Babel will convert ECMAScript2015+ code and JSX code to ECMAScript2015 du ...

Serving static files in Next.js with specific extensions without triggering a download

I'm facing an issue where I need to serve the stellar.toml file in domain/.well-known/stellar.toml with the content type as text/plain. The current configuration works only when the stellar file is saved without an extension. It is essential for me t ...

What is the reason for all the buttons activating the same component instead of triggering separate components for each button?

I am facing an issue with my parent component that has 3 buttons and 3 children components. Each button is supposed to open a specific child component, but currently all the buttons are opening the same child component when clicked. The children components ...

The Graphql mutation successfully updated the user data, however, it mistakenly changed the password resulting in me being unable to log in after

I am relatively new to this so please bear with me. Every time I execute the mutation, I can see the changes in mlab and the user gets updated successfully. However, when I log out and try to log back in, I encounter difficulties. My suspicion is that the ...

Having trouble with Next Auth getSession in api routes

When I utilize getServerSideProps to access APIs, calling getSession in the getServerSideProps() function returns a valid object. export async function getServerSideProps({ req }) { const session = await getSession({ req }); // works However, if I call ...

How to Delete an Edge on React's Google Maps?

I am looking for a way to eliminate the edges from React Google Maps when it is drawing the boundary. <GoogleMap onClick={(value)=>{ props.map_data.getClassName(value) }} defaultZoom={9} defaultCenter={props.locationCoords} defaultOption ...

Is it possible to modify the defaultProp mouseEvent of the ClickAwayListener in SnackBar from 'onMouseUp' using Material-UI?

Utilizing Snackbar from Material-UI, I encountered the ClickAwayListener within it. The default prop for mouseEvent in ClickAwayListener is set to 'onMouseUp', but I need it to be 'onMouseDown'. If I were directly using ClickAwayListe ...

Invoke React Component Function using onclick in dangerouslySetInnerHTML

I'm new to React and I have a contenteditable div with dangerouslySetInnerHTML as the child, for formatting user input at runtime. When a specific span is clicked inside the HTML, I want to update a variable in the parent component using setState. Is ...

Trouble with displaying list bullets in jQTouch framework

I'm currently experimenting with jQTouch for a web app designed for iPhones. However, I am facing an issue where I want the content on the pages to display normal bullet lists instead of being styled as bars in the jqt theme. To achieve this, I am att ...

What is the best way to combine a top <div> with a bottom <div> in an image without creating unsightly white gaps?

I need help overlapping two divs on top of an image in HTML. The first div should cover part of the top area of the image, while the second div should cover part of the bottom area of the image. These divs should be displayed over the image without leaving ...

Unable to resolve TypeScript error: Potential 'undefined' object

Here is the code snippet that I am working with: const queryInput = useRef() const handleSubmit = (e: FormEvent<HTMLFormElement>) => { e.preventDefault() if (queryInput && queryInput.current) { console.log(`queryInput.cur ...

Tips for converting a number into a percentage with two decimal places using FormatJs Message Syntax

With the react-intl library, I am encountering a message that looks like this: serviceFee: { en: 'Service fee: ({fee, number, percent})', ... }, Upon calling <FormatMessage id="serviceFee" values={{ fee: 0.0625 }} /> I anticipate th ...

Top recommendation for ensuring that a component is not being displayed

Imagine a scenario where a component returns null in the render method based on a specific prop. How can you effectively use expect to ensure that the component is not rendered? For example: import React from 'react'; import { render, fireEvent ...

A guide on converting a React component to plain text output

Apologies for the seemingly silly question. I am currently working on a React app and documenting my components. I am struggling to figure out how to insert my component as plain text. For example: import Input from "../components/input"; funct ...

Can an image be allowed to overflow outside of a div without changing the div's size?

Starting Point I am in the process of designing a layout with Bootstrap 4. Here's a rough representation of what I am aiming for: https://i.sstatic.net/7QTpk.jpg And here is the basic structure: <div class="row"> <div class="col-12 c ...