What is the best way to toggle DOM classes in React using Material-UI components?

Currently utilizing Material UI alongside React, I have a div element:

<div className={classes.div}></div>

I am attempting to dynamically add a conditional class to it:

<div className={classes.div + divActive ? `${classes.div}__active` : ''}></div>

Unfortunately, the second example is not functioning as expected - it consistently displays

<div class="makeStyles-div-2__active"></div>
instead of:

When divActive is false:

<div class="makeStyles-div-2"></div>

When divActive is true:

<div class="makeStyles-div-2 makeStyles-div-2__active"></div>

Can you help me figure out what could possibly be missing? I attempted enclosing classes.div in an additional template literal like so:

<div className={`${classes.div}` + divActive ? `${classes.div}__active` : ''}></div>

However, the outcomes remain unchanged. Interestingly, upon removing the initial class (classes.div), the toggle for divActive appears to be functioning correctly by switching between active and inactive states. This leads me to believe that the issue lies within the first variable - but where exactly is the error?

Answer №1

To enhance readability, enclose the ternary condition in parentheses and include extra space when the function divActive evaluates to true

<div className={classes.div + (divActive ? ` ${classes.div}__active` : '')}></div>

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

Is there a way to have text appear in a popup when I reach it while scrolling?

Is there a way to make the textblocks on my website increase in size or pop up when I scroll down to them? I've attempted to search for a solution online but have been unsuccessful in finding one. ...

Utilizing AMAZON_COGNITO_USER_POOLS in conjunction with apollo-client: A comprehensive guide

Struggling to populate my jwtToken with the latest @aws-amplify packages, facing some challenges. Encountering an error when attempting to run a Query: Uncaught (in promise) No current user It seems that when using auth type AMAZON_COGNITO_USER_POOLS, I ...

In a Twitter Bootstrap environment, the button cursor transforms into an I-beam when activated

After utilizing twitter bootstrap to construct a small blog site and integrating a third-party file upload application into the project, I encountered an issue. The CSS files in the file uploader style the "upload button," but when my cursor hovers over it ...

Create a regular expression that permits a sequence of numbers (either integer or decimal) arranged in groups of up to five, with each

Is it possible to create a regular expression that allows integers and decimals? var reg = /^((\s*)|([0-9]\d{0,9}(\.\d{1,3})?%?$))$/.; How can users input 0 to 5 groups of integers and decimals separated by |? Updated: This regex sh ...

Fetching real-time Twitter search feeds through dynamic AJAX requests

Previously, I successfully used JSON to retrieve hash tag feeds from Twitter and Facebook. However, currently the feeds are not updating dynamically, indicating a need for Ajax implementation. Unfortunately, my lack of knowledge in Ajax is hindering this ...

Incorporating Node modules within a Spring Boot executable JAR

I am currently working on a Spring Boot application with a React front end. In my project, I have node dependencies managed by package.json and Spring Boot dependencies handled by Gradle. As I prepare to build a jar for my production environment, I am unc ...

What could be the reason behind CSS styles applying only when inserted within a style tag in my form, and not in the linked CSS file?

I want to express my gratitude for finding a solution to positioning Validator CallOuts on a web form through this question regarding repositioning the AJAX toolkit's CalloutExtender control. Does anyone know why applying CSS classes directly within ...

What is the best way to split key and value into separate array objects using JavaScript?

Here's a snippet of code I am working with: let obj = {EdadBeneficiario1: '32', EdadBeneficiario2: '5'} var years = []; let i; for (i= obj;i<=obj;i++) { years.push({ edad_beneficiario : i }) } When I run this code, the output i ...

Clicking on a button will trigger the opening of a modal dialog

I encountered an issue with the following code: <sepa-modal ref="sepaModal" /> <b-card id="show-btn" class="card-modal" @click="openSepaModal()" > </b-card> openSepaModal ...

Using enzyme mock function prior to componentDidMount

When it comes to mocking a function of a component using Jest, Enzyme, and React, the process typically involves creating a shallow wrapper of the component and then overloading the function as needed. However, there seems to be an issue where the componen ...

Modifying the Position of the Search Box within DataTables by Manipulating DOM Elements

As a newcomer to the jQuery datatables plugin, I am still learning how to use it effectively. I have connected the plugin to my tables using the following code: $(document).ready(function() $('#table_id').dataTable({ }); }); ...

The worldwide delineated modification

How can I customize the global theme to affect all components with variant = 'outlined' style? I also want to modify events such as focus, hover, etc. "@material-ui/core": "^3.9.2", ...

Display a notification depending on the condition met

I have multiple backend conditions that I need to check in order to display an alert within an antd modal. The initial code looks like this: Modal.confirm({ centered: true, title: 'Sorry, you cannot create Menu without satisfying the following ...

Surprising Regex Match of ^ and special character

My regular expression is designed to break down calculator input strings, such as 12+3.4x5, into individual tokens like 12, +, 3.4, x, and 5 Here is the regular expression I am using: \d+\.?\d+|[\+-÷x] However, I am encountering une ...

Ways to display JSON in a structured format on an HTML page

Is there a way to display JSON in a formatted view on my html page? The JSON data is coming from a database and I want it to be displayed neatly like the following example: { "crews": [{ "items": [ { "year" : "2013", "boat" ...

The HTML element does not expand to fill the entire page

I recently encountered a problem with my website. Everything was functioning smoothly until I decided to add some in-page links to a large page. After adding the links, the background no longer stretched the entire length of the page. When scrolling down, ...

Encountering an issue where I am unable to access properties of undefined (specifically 'up') within Material UI styling

I encountered an error message Uncaught TypeError: Cannot read properties of undefined (reading 'up') while executing the code snippet below: I am having trouble with compiling my react js Code Snippet from Index.js import React from 'react ...

Issue in IE with click event not firing from parent page

Currently, I am facing an issue with a filter on one of my website's pages that is designed to display various products. My goal is to set it up so that when a button from an external page is clicked, the user will be redirected to the product page wh ...

Is there a way to adjust this callback function in order to make it return a promise instead?

This script is designed to continuously attempt loading an image until it is successful: function loadImage (url = '', callback = () => {}) { utils.loadImage(url, () => { callback() }, () => { loadImage(url, callback) }) } ...