What is the best way to adjust the background color of Material UI's theme based on different screen sizes?

Having trouble replacing hard-coded CSS breakpoints with Material UI theme settings.

@media screen and (min-width: 0px) and (max-width: 400px) {
    body { background-color: red; }
}
@media screen and (min-width: 401px) and (max-width: 599px) {
    body { background-color: blue; }
}
@media screen and (min-width: 600px) {
    body { background-color: green; }
}

Trying to implement the same breakpoints in a Material UI theme but running into issues. Here's what I've attempted so far:

const defaultTheme = createMuiTheme();
export const theme = createMuiTheme({
    palette: {
      background: {
        [defaultTheme.breakpoints.down('sm')]: {
            default: 'red'
        }
      },
    }
});

Not sure if this approach is supported by Material UI. Any insights would be appreciated.

Answer №1

To understand how this code snippet utilizes theme.palette.background.default, take a look at the link provided. The syntax you attempted will simply create a new property in theme.palette.background that Material-UI won't recognize.

An alternative approach would be to define custom entries in your theme like so:

const theme = createMuiTheme({
  palette: {
    background: {
      xs: "red",
      sm: "blue",
      md: "green"
    }
  }
});

You can then utilize these customizations in your styles:

const styles = theme => ({
  "@global": {
    body: {
      [theme.breakpoints.up("md")]: {
        backgroundColor: theme.palette.background.md
      },
      [theme.breakpoints.down("sm")]: {
        backgroundColor: theme.palette.background.sm
      },
      [theme.breakpoints.down("xs")]: {
        backgroundColor: theme.palette.background.xs
      }
    }
  }
});

For more detailed implementations, check out this CodeSandbox example.

For a related query, refer to this post: Overriding default styles on divs, p's, and body with createMuiTheme

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

Creating separation between a dropdown menu and its corresponding button

I'm dealing with a situation where I have a button that reveals a hidden droplist upon hover. The problem is that there is no space between the button and the droplist, causing interference with the functionality. My attempt to create some distance b ...

Easily automate button clicks on a new tab website

Seeking assistance below, following codes are sourced from "example.com" as assumed: <a href="http://www.example.org" target="vo1" onclick="gp(1)" rel="nofollow">Click Me</a> Upon clicking on ...

Error: Unable to invoke hook function correctly while organizing my code structure

As a beginner in React, I decided to organize my code while building a blog homepage. Initially, I started by coding the Header in index.js, which worked smoothly. However, when I attempted to restructure my code by dividing it into separate files and cla ...

Selecting the first li element using JQuery selectors

Can anyone help me with creating an onclick event that triggers when the user clicks on the first list item which is labeled as "Any Date"? I am looking to use jQuery to target this specific element. <ul id="ui-id-1" class="ui-menu ui-widget ui-widge ...

Verify the entered information in the input field and showcase it in the display box after pressing the ENTER key

I need to display selected values of a tree structure in a show box on the other side of the page using code. However, I also need to include HTML input boxes in some lines of the tree structure so that users can input data. The challenge is getting the in ...

Issue: The data type 'void' cannot be assigned to the data type 'ReactNode'

I am encountering an issue while calling the function, this is just for practice so I have kept everything inside App.tsx. The structure of my class is as follows: enum Actor { None = '', } const initializeCard = () => { //some logic here ...

Encountering an error message stating "Module '@material-ui/core/es' not found" while executing the material-ui codemod

I'm attempting to implement the top-level-imports codemod from the following source: https://github.com/mui-org/material-ui/blob/master/packages/material-ui-codemod/README.md#top-level-imports. To start, I executed npm install -D @material-ui/codemod ...

What is the correct method for replacing a static page with an "outdated page"?

My website features several static promotional pages. However, I am facing the challenge of displaying an expired page once a promotion has passed. How can I achieve this seamlessly with static pages in NextJS? On my first attempt, I checked for expiratio ...

Error encountered in App.js on line 29: Unable to access the property 'map' as it is undefined

Currently enrolled in the University of Helsinki Full Stack Open course, I am facing a challenging error while working on my React web app. The app retrieves data from the Rest Countries API (https://github.com/apilayer/restcountries) and I am trying to di ...

What is the best way to add a URL dynamically when a click event occurs?

Here is the code where I am making an API call: export const filteredProducts = (e) => { const radio = e.target.checked; return dispatch => { dispatch({type: actionTypes.TOGGLE_LOAD}); axios.get(radio ? `/store?limit=9&skip=0&subc ...

Is your margin not functioning correctly? Is padding taking on the role of margin?

One issue I'm encountering is that the margin isn't behaving as expected in this example. The padding seems to be working like margin should. Why is that? Print Screen: https://i.stack.imgur.com/N1ojF.png Why is it that the margin in the h3 ta ...

How come the parameters in my function are being displayed as boolean values in JSDocs when that is not the intended behavior?

I am documenting my journey of following the React tutorial for tic-tac-toe, and I'm puzzled as to why the parameters of my function are showing up as boolean values in JSDocs when they are not supposed to. When I hover over the function with my curs ...

Experiencing network request failure on one specific URL while using React Native for iOS, but having no issues with other URLs

I'm facing an issue in my React Native app while trying to make an API call using the following code: test = async () => { try { let a = await fetch('https://rxapitest.alliancepharmacygroup.ca:12345/', { method: 'G ...

Having difficulty with uploading images in the correct size on the AWS S3 server

When I upload an image to AWS S3 bucket, the image size is only showing as 6 Byte, which is not the actual size of the image. I am confused why the image is not uploading with its actual size. What could be causing this issue? interest.js file Inter ...

Utilizing jQuery for dynamic horizontal positioning of background images in CSS

Is there a way to set only the horizontal background property? I've tried using background-position-x and it works in Chrome, Safari, and IE, but not in Firefox or Opera. Additionally, I would like to dynamically set the left value of the position. ...

Eliminate item upon alteration of redux state

I am facing an issue with updating a component when removing an element from the Redux state. Here is my component: const mapStateToProps = state => ({ products: state.shoppingBasket.list, }); const ShoppingBasket = React.createClass({ propTypes: ...

How can I extract the page's output using JQuery?

Being a rookie in this area, I am eager to learn how to extract specific content from a page using AJAX in JQuery. Currently, I have been able to fetch the data of a page and display it as text: $.ajax({ type: "POST", url: "myfile.html", su ...

Tips for conditionally displaying a Next.js component depending on the authentication status of the user making the request from Firebase

Note: Currently, I am implementing Next.js 13 within the app/ directory. I have been delving into Firebase and Next.js and am encountering difficulties grasping a particular concept. Imagine I have a Home() component structured as follows /app/page.jsx e ...

What is the best way to apply fill to SVG using Tailwind CSS?

I tried using the code provided, but unfortunately, I was unable to Override the fill. The issue seems to have been resolved, but can someone help me achieve this using tailwind CSS? <div className=""> <svg className="text- ...

Testing the axios mock with a 400 response does not result in the expected value being returned

Currently, I am utilizing nock to simulate my ajax call with axios. Below is the code snippet that I am working with: describe("unSuccessful rest call",()=>{ it('should dispatch types: SET_DROP_DOWN_CHECK_STATUS in order ', () => ...