Ways to replace CSS classes created using makeStyles

To clarify, my development environment is using MUI version 4.12.3. Inside file A, I have a simplified code snippet for a functional component, along with the usage of makeStyles to style a JSX element within the return statement (not displayed here). Everything functions correctly in this scenario.

const useStyles = makeStyles((theme) => ({
  content: {
    minHeight: '100vh',
  },
}));

Now, moving on to file B, the objective is to modify the CSS class content based on the value of isDesktop. Is it feasible or recommended to do so? Below is an attempt that didn't yield the expected outcome:

const useStyles = makeStyles({
  content: {
    minHeight: (props) => (props.isDesktop ? '100vh' : '112vh'),
  },
});

//And within the functional component:
const isDesktop = useMediaQuery(Theme.breakpoints.up('sm'));
const classes = useStyles({ isDesktop });

It's important to note that the primary goal in file B is to alter the CSS class content, without rendering the JSX component. The classes variable remains unused in this context as shown above.

Answer №1

To achieve this functionality, we can utilize a limited number of hooks. Let's assume that the name of our functional component is "MyComponent" and our material component is called "MaterialComponent". The first step is to import the useWindowSize hook, which will allow us to determine the window size and distinguish between desktop and mobile screens. Within the makeStyles function, we create two classes for setting the minimum height for desktop and mobile views. By using a simple if-else statement, we conditionally apply these classes to the className prop of MaterialComponent. Below is the code snippet:

1. Define two classes using makeStyles

const useStyles = makeStyles((theme) => ({
  contentDesktop: {
    minHeight: '100vh',
  },
  contentMobile: {
    minHeight: '110vh',
  }
}));

2. Import the useWindowSize hook

import useWindowSize from "hooks/useWindowSize";

3. Functional component code

const MyComponent = () => {
  const classes = useStyles();
  let myClass = "";
  const width = useWindowSize();
  const isDesktop = width >= 1024;
  const isMobile = width <= 600;
  
  if (isDesktop) {
    myClass = classes.contentDesktop;
  }
  if (isMobile) {
    myClass = classes.contentMobile;
  }
  
  return (
    <MaterialComponent className={`${myClass}`} />
  );
}

Answer №2

If you need to use this function outside of your functional component, you can easily export it.

export const customizeStyles = (isDesktop) => {
  return {
    presentation: {
      minHeight: isDesktop ? "100vh" : "112vh",
    },
  };
};

Then, simply apply your customized styling wherever needed.

const isDesktop = utilizeMediaQuery(Theme.breakpoints.up('sm'));

...
  <SomeOtherMuiComponent sx={customizeStyles(isDekstop)} />

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

What is the best way to create a React text box that exclusively accepts numeric values or remains empty, and automatically displays the number keypad on mobile devices?

While there are numerous similar questions on StackOverflow, none of them fully address all of my requirements in a single solution. Any assistance would be greatly appreciated. The Issue at Hand Within my React application, I am in need of a text box tha ...

I am attempting to store the primary array in local storage, but unfortunately, the value is not being saved within the React context API

I attempted to store the main array in local storage and retrieve it as global state, but I am facing an issue where the data is not being saved in the local storage. This file represents my context. import { createContext, useReducer, ReactNode, FC, use ...

A guide on implementing arrow links in D3.js

i am struggling to add an arrow to one end of a link in my code. even though the links are functioning correctly, i can't seem to figure out how to draw arrows successfully. any assistance on how to implement this would be greatly appreciated. thank y ...

Guidelines for utilizing basepath for specific pages in NextJS

I'm currently working on a NextJS application using version 13 and I have a question regarding setting the basepath for specific pages only. For example: "/auth/*" --> should not display the basepath "/remaining-pages" --& ...

MUI: The color utility previously known as 'fade' has been updated to 'alpha' in order to more accurately reflect its purpose within material-table

While working with material-table (latest version 1.69.3) and MUI v5.0.6 to create an editable table, I encountered this message in my console: https://i.stack.imgur.com/GXKl3.png The error mentions importing alpha, but as fade from the npm package mater ...

After performing an action with Redux, the error message ""Cannot access properties of 'undefined'" is displayed

I am currently developing a Shopping List App using React/Redux. I am facing issues with removing items from a list. When I trigger the 'removeItem' action, the page no longer recognizes the object that represents the list (which was originally s ...

Executing a jQuery script on various elements of identical types containing different content (sizes)

I am currently working on a jQuery script that will center my images based on the text block next to them. Since I am using foundation 5, I have to use a jQuery script to override the CSS instead of using vertical-align: middle. The script looks like thi ...

Arrangement using the display property of inline-block not following a linear direction

I'm experiencing some issues with the arrangement of elements on this page: When the viewport width is around 800px, the layout appears misaligned. Some lines have only a few bottles even though there is space for more. Is there a solution to this pr ...

Error code -4058 ENOENT indicates that the file or directory does not exist. This issue is usually caused when npm is unable to locate a specific file

Trying to start a react project on my D: drive while having node installed on the C: drive resulted in an error: D:\react> npm start npm ERR! code ENOENT npm ERR! syscall open npm ERR! path D:\react/package.json npm ERR! errno -4058 npm ERR! ...

Is my data secure in Node.js RAM?

I have developed a web application that enables users to create personal pages using Express and Node.JS. Each page is represented as an object, allowing for the creation of new ones with the syntax: new privatePage(name, pswd). As a result, all passwords ...

What's the best way to update the state with each click?

Hi there! I've created a tab feature that should change its state with each click on the button. Unfortunately, it seems to be changing state globally instead, resulting in multiple tabs appearing at once with just one click. function Tabs() { const ...

Adding a vertical menu in PHP is a great way to enhance the

<ul id="verticalmenu"> <li><a href="http://www.yourlink.com/">Home</a></li> <li><a href="http://www.yourlink.com/">Vertical Menu</a></li> <li><a href="http://www.yourlink.com/">Dro ...

Chrome and FireFox Encounter Ajax Functionality Issues

This script that I have created works flawlessly on Internet Explorer! However, it encounters a few issues when used on Chrome and Firefox. Specifically, it only functions correctly for the first action performed, but fails to do so for subsequent actions. ...

What does the term "progressive framework" refer to?

Recently, I've delved into the world of frontend frameworks such as Vue.js and AngularJS. In my research, I keep stumbling upon the term "Progressive Framework," but its true meaning still eludes me. Vue.js claims it can easily integrate with simple H ...

Sending a request to a JSON file using Ajax

I have 2 questions: 1. I am trying to run this file, but it is not giving any errors or showing results. Please help me identify the problem. 2. I added a dropdown menu in my HTML file, but I'm unsure how to use it to display a list of names. Any sugg ...

What's the best way to refactor the `await nextEvent(element, 'mousemove')` pattern in my code once it is no longer necessary?

Within my React component, the code includes the following: class MyComponent extends React.Component { // ... trackStats = false componentDidMount() { this.monitorActivity() } componentWillUnmount() { this.trackStat ...

The method to extract the followers of an Instagram account using node.js, cheerio, and InstAuto/Puppeteer

Currently, I am attempting to develop a program that generates lists of users who follow specific profiles, and vice versa. Since the Instagram graph API is now inactive, this task has become quite challenging. Despite identifying the correct div element, ...

ReactJS: Communicating changes in Child component state to Parent component state

I'm currently working on a ReactJS project where I aim to create a reusable component consisting of a checkbox and a textfield input (such as a Todo list item). The current structure of my React solution looks something like this: <Parent > --| ...

Menu options moved to the right of the screen

I am encountering a small issue with my dropdown menu that I can't seem to solve. The first item in the dropdown menu appears correctly, but the second item is slightly shifted to the right. It seems like the margin-right applied to the link may be c ...

Having trouble with updating links in HTML pages?

I'm having trouble updating all the links in my HTML file. The code I have isn't working as expected. var fs = require('fs'); fs.readFile(__dirname + '/index.html', 'utf8', function(err, html){ if(!err){ html = ...