Reputation: 31
In material UI
, the theme can be adjusted and/or overridden using the createMuiTheme
function. This is the full file in which I am doing so:
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 global styling applied to the body is confirmed working- I can see the blue border. However, nothing I try will get the background image to work.
Normally, I would uncomment the import statement at the top: import wood from './static/wood.png';
and then change the CSS line to:
backgroundImage: `url(${wood}),`
However, the import statement alone is causing a crash:
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.
When I instead attempt to use a url for the image (shown above), it is always a 404 error. My file structure places the image in src > static > wood.png
, but I get:
http://localhost:3000/static/wood.png 404 (not found).
I've tried dozens of possible path
variations, but none have worked, and all my efforts to research the proper path just indicate that I'm already using the correct path.
Is it only possible to add a background image to the body using Material UI theme customization when the background image is hosted on a separate server?
The only working examples I've found do it that way (like this one: https://codesandbox.io/s/v30yq681ql), but it seems like there must be a way to use an image stored locally.
Or if the problem really is that my relative path is incorrect, what can I do to find out what the correct one would actually be?
If there is a better way to add a background image to a page with Material UI
that would work too, though I haven't seen any other way to do it than a global override of the body tag.
Upvotes: 3
Views: 8309
Reputation: 1028
If you put your image within the src
folder instead of static
, e.g.
src/components/wood.png
Reinstate your import like:
import wood from './components/wood.png';
and then put the backgroundImage
to:
backgroundImage: `url(${wood})`,
that should work. The same configuration (with different filename, but in the same location) works for me.
Upvotes: 6