What is the best way to selectively add multiple classes to a single Material UI classes attribute based on certain conditions?

I am trying to use the Material UI Drawer and wish to add a class named "paperStyle" to the classes prop with the rule name "paper" and then, under certain conditions, apply an additional class called "specialPaperStyle" for specific users. However, I have struggled to assign two classes to the paper rule, let alone conditionally apply it. Does anyone have any suggestions on how to solve this issue?

Highlighted below are the main portions of my code:

Styles

const useStyles = makeStyles(theme => ({
  paperStyle: {
    width: drawerWidth,
    boxShadow: 'inset 0 0.3rem 1.5rem rgba(0,0,0,0.19)',
    color: theme.palette.primary.main,
    [theme.breakpoints.up('lg')]: {
      minHeight: '100%',
      position: 'relative',
    }, 
  },
  specialPaperStyle: { 
    backgroundImage: 'linear-gradient(to bottom right, #27133f, transparent)',
},
}));

Material UI Drawer

<Drawer
   classes={{
     paper: classes.paper,
   }}
 >
      Contents of drawer
</Drawer>

The current setup successfully applies my paperStyle class, but how do I go about conditionally applying the specialPaperStyle class to paper? For example:

Attempted Solution:

<Drawer
   classes={{
     paper: {`${classes.paperStyle isSpecial && $classes.specialPaperStyle}`},
   }}
 >
      Contents of drawer
</Drawer>

Thank you in advance,

Katie

Answer №1

One useful feature of material-ui is its integration with the clsx package, which simplifies the process of adding classes based on specific conditions. You can provide multiple class arguments or even objects that will apply the class key if the value is true:

import clsx from 'clsx';

<Drawer
   classes={{
     paper: {clsx(classes.paperStyle, {[classes.specialPaperStyle]: isSpecial})},
   }}
 >
      Contents of drawer
</Drawer>

Check out the documentation for more information on using clsx in material-ui.

Answer №2

What do you think of this?

REVISED

<Drawer
   classes={{
     paper: {`${classes.paperStyle} ${isSpecial ? classes.specialPaperStyle : ''}`},
   }}
 >
      Items inside drawer
</Drawer>

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

Tips on how to show a personalized <Errormessage> within a Formik field component while turning off the standard message

In my current web project, I am utilizing a combination of React, Material-UI, Formik, and formik-material-ui. Specifically, I have implemented a Formik form that includes validation using yup. const schema = yup.object({ name: yup.string().trim().low ...

When a td element is clicked, the Textbox will also be clicked

Similar Question: Dealing with jQuery on() when clicking a div but not its child $(oTrPlanning).prev().children('td').each(function () { this.onclick = setCountClick; }); When a TD element is clicked, the function setCountClick() i ...

When refreshing, the React state object is mysteriously transforming into "[object Object]" while utilizing sessionStorage

Currently, I am working on a practice fullstack ecommerce application using Postgres, Express, and React as part of my fullstack course. My inquiry pertains specifically to React. Upon logging into the application, I can successfully manage a cart in the ...

Unable to properly connect my CSS file to the header partial

I am struggling to include my CSS file in the header partial Here is the link I am using: <link rel="stylesheet" href="stylesheets/app.css"> This is what my directory structure looks like: project models node_modules public stylesh ...

The React application deployed on Heroku is experiencing difficulties when trying to send a POST request

While experimenting with the Chatkit API, I encountered an issue when deploying a React app to Heroku. Everything worked perfectly on my local machine, but upon pushing it to Heroku, I started receiving errors such as "Failed to load resource: net::ERR_CON ...

Exploring Gatsby's versatility through the use of multiple GraphQL versions alongside the powerful

Starting my Gatsby journey and experimenting with the gatsby-source-pg plugin. Encountering issues with different graphql versions. Reached out to the plugin author on GitHub for assistance, and they were extremely helpful in addressing my concerns. Howev ...

Tips for reducing image file size using ImageMinimizerWebpackPlugin in Next.js (webpack 5)

When attempting to use this plugin for image compression, I am encountering an issue where the build process completes successfully, but the images remain uncompressed. As a beginner with webpack, I'm unsure of what might be causing this problem. Cou ...

The absence of the function crypto.createPrivateKey is causing issues in a next.js application

For my next.js application, I am utilizing the createPrivateKey function from the crypto module in node.js. However, I encountered an issue as discussed in this thread: TypeError: crypto.createPrivateKey is not a function. It seems that this function was a ...

Steps to animate a div expanding to fit its content dimensions

I'm looking for a way to animate the opening of a div so that it adjusts to the size of its content. The content is fetched from a separate search using .load, which means it could be just a single line (no result) or multiple results that vary in hei ...

Display the content of an md-dialog with a scroll bar

I am experiencing a problem with printing a long report created using md-list displayed in a md-dialog. When I attempt to print it, only the section that is currently visible on the screen gets printed instead of the entire length of the md-list. I have at ...

JavaScript progress bar with extended duration, inspired by the success-oriented approach

Currently, I am in search of a unique solution or plugin that can replicate the same effect as Kickstarter's crowd fund long term progression bar. It seems like existing solutions only offer short term dynamic progress bars that indicate the percentag ...

Is there a reason behind why this functionality is only applicable to a class component and not a functional one?

Essentially, I am working with multiple buttons and aiming for the user to be able to select more than one button at a time. I attempted to achieve this using a functional component by storing the button states as objects with the useState hook. While the ...

Attempting to display items using the map method, pulling in text from an array

I am working with an array state that tracks the text entered by the user in a text field. My goal is to display this text within a component so users can see what they have previously entered. However, I am facing an issue with my Hashtags component when ...

list without specific order spacing

I have implemented an unordered list in the footer section of my HTML document. Within this list, the first two items consist of social media logos displayed as images. To enhance their visibility and prominence within the footer, I have assigned them a wh ...

Top method for directly converting SVG to JSX within a popular React component library

Currently, I am exploring the most effective method to directly import SVG images as JSX components into my React common component library. By "common component library," I am referring to a distinct package that houses shared components utilized by variou ...

Using the useState hook to manage an array of boolean values in a React

As a beginner developer in React Native, I am facing a design pattern issue. I have multiple TouchableOpacity components in the same component and I need to maintain this structure. Each TouchableOpacity has an onPress function that changes its backgroun ...

Utilizing a React component as a function: A step-by-step guide

I am looking to implement a material ui dialog that can handle the result from JavaScript for a simple yes/no prompt. This is how I envision it working: <MyPromptComponent /> { MyPromptComponent.show('Do you really want to?').then((res ...

ReferenceError: _jquery2.default.ajax is not a function" encountered in a React Native application

I have been attempting to use jQuery to retrieve xml data from an internal website. My expo project setup is quite basic and resembles the following: import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; imp ...

HTML page filled to the brim with data tables

Wrapping up a midterm assignment for an HTML course and facing an issue on the final page. The table is overflowing to the right when the browser isn't maximized, and I'm stumped on how to solve it. Any suggestions? Unfortunately, unable to shar ...

Utilizing the Parent's Props in ReactJs: A Comprehensive Guide

I am currently utilizing reactjs version 16. My objective is to create a wizard that can be reused anywhere on my website, providing flexibility and convenience. Take a look at the code I have implemented: export default class Website extends Component ...