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.