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

Exploring nested components traversal in React

In my project, I have created a product component that displays the products' name, price, and description. const Product = (props) =>{ return( <div> <p>Price: {props.price} </p> <p>Name: ...

Alert for JavaScript Increment (++) Operation

While reviewing my code using jslint, I noticed a warning regarding the increment operator: var x = 1; x++; Warning: Unexpected expression '++' in statement position. According to the documentation: "They are second only to faulty archi ...

Efficiently Filtering User Input and Other Things

Imagine I have a setup for organizing a television guide like this: <div class="day"> <p>A Date</p> <div class="time"> <p>A Time</p> <div class="show"> <p>A Show</p> ...

Tips for transforming a scroll element into the viewport using Angular 2+

This is a sample Here is a component with a list of items: class HomeComponent { text = 'foo'; testObject = {fieldFirst:'foo'}; itemList = [ '1', '2', '3', & ...

Automating the process of running npm start on page load: A guide

Recently, I've been delving into learning npm in order to incorporate it into a website. I'm curious about how exactly it is used within a website - do you typically need to execute the command "npm start"? How does this integration work for a li ...

The concept of nested views in Angular UI-Router allows for a

How can I successfully implement nested views, where after logging in the user is redirected to in.html, and all links within in.html are directed to a ui-view? Currently, all links redirect to a new page. index.html <!-- more HTML --> <body ng- ...

Ways to append multiple values to an object ID in mongoDB at a later time

I have a pre-existing object ID in my MongoDB database, and I am looking to add more values inside it in the future. Here is an example of my current MongoDB structure: [{ label: 'colors', options: [ { label: 'Bl ...

Unable to locate item by its identification number

Search for results in the index and return them. Method: async fetchIndex(req,res){ const userResults = await Usuario.find(); res.json(userResults); }, Route: routes.get('/api/usuarios', Usuario.fetchIndex); Having trouble ...

Using javascript, hide or show a div without using jquery or the display:none property

I am looking for a way to show/hide a div up and down, but I have some requirements: I cannot use jQuery: toggle(), slideToggle(), fade, animate, etc. all use display: none, and I need the div to still occupy space in the DOM (I will be processing things ...

Extracting values from URL query parameters in Vue.js

When dealing with Vue.js callback URLs, I encounter situations where I need to extract a parameter value from the URL. For instance, consider this return URL: http://localhost:8080/#/sucesspage?encryteddata=abdeshfkkilkalidfel&9a I attempted to retrie ...

Implementing Knockout.js with JqueryUI Autocomplete: Access the complete object instead of just the value

I have implemented a custom binding for a JQueryUI auto complete feature that works well. However, I am looking to modify it so that it returns the Item object, which can then be pushed to another array. Can someone provide guidance on how to achieve this ...

Using useState in ReactJS does not allow setting state data

I am working with a react component that handles agreements. import React from "react"; import { AgreementInfo } from "../../../../models/shop"; import { MdClose } from "react-icons/md"; import moment from "moment"; ...

Tips for retrieving a child component's content children in Angular 2

Having an issue with Angular 2. The Main component displays the menu, and it has a child component called Tabs. This Tabs component dynamically adds Tab components when menu items are clicked in the Main component. Using @ContentChildren in the Tabs comp ...

What could be causing the misalignment of the Datepicker calendar in Material UI?

I have integrated a datepicker using the library "@mui/x-date-pickers/DatePicker". import { DatePicker } from "@mui/x-date-pickers/DatePicker"; import { AdapterMoment } from "@mui/x-date-pickers/AdapterMoment"; import { Locali ...

VueJS does not refresh other components in the application

I am working with two components. Let's start with Component 1: <template> <div> <div class="form-group"> <label for="group">Category</label> <select name="category" v-model="category" @change="setCategory(ca ...

What is the proper way to construct a URL with filter parameters in the RTK Query framework?

I am facing difficulty in constructing the URL to fetch filtered data. The backend REST API is developed using .Net. The format of the URL for filtering items is as follows: BASE_URL/ENDPOINT?Technologies=some-id&Complexities=0&Complexities=1& ...

Dealing with an endless loop caused by a promise in AngularJS's ui router $stateChangeStart event

I am currently working on implementing authentication in my Angular application and I want to redirect to an external URL when a user is not logged in (based on a $http.get request). However, I seem to be stuck in an infinite loop when using event.prevent ...

The specified selector is invalid or illegal in HTMLUnit

Attempting to mimic a login using htmlunit has presented me with an issue despite following examples. The console messages I have gathered are as follows: runtimeError: message=[An invalid or illegal selector was specified (selector: '*,:x' erro ...

Create an HTML and CSS code that allows you to split paragraph text into columns within a

I am seeking a way to create dynamic paragraph column text using only the Here is an example of how it could be displayed in HTML: <div> <p> Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantiu ...

Issue with React Ref: Invariant Violation when trying to addComponentAsRefTo

I'm encountering an issue while attempting to add a ref to a React component. The error message I'm seeing is as follows: invariant.js:39Uncaught Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding ...