The MUI makeStyles() class has been implemented, yet the styles are not being displayed when using classList.add('class-name')

Currently, I am utilizing MUI makeStyles() to create a series of CSS classes. Within these classes, I am dynamically including and excluding one specific class to my Box element during file drag-and-drop events.

The class is successfully added, as I can observe it being applied while dragging a file over my element. However, the styles within the class are not reflecting on my element. I'm unsure about what could be causing this issue and any guidance would be greatly appreciated.

Below is an excerpt from my code:

const useStyles = makeStyles({
  imageUploader: {
    width: '100%',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    gap: '8px',
    padding: '24px 16px',
    border: '1px dashed #AAAAAA',
    borderRadius: '4px',
    cursor: 'pointer',
  },
  imageUploaderDrop: {
    background: '#e4e4e4',
  },
});

export default function ImageUploader() {
  const styles = useStyles();
  const imageUploaderContainer = useRef<HTMLDivElement>(null);
  const imageUploader = useRef<HTMLInputElement>(null);

  const classList = () => imageUploaderContainer.current?.classList;

  const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    const file = e.dataTransfer.files[0];
    classList()?.remove('imageUploaderDrop');
  };

  const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    if (!classList()?.contains('imageUploaderDrop')) {
      classList()?.add('imageUploaderDrop');
    }
  };

  const handleDragLeave = () => {
    if (classList()?.contains('imageUploaderDrop')) {
      classList()?.remove('imageUploaderDrop');
    }
  };

return (
    <Box
      className={styles.imageUploader}
      onClick={() => imageUploader.current?.click()}
      onDrop={handleDrop}
      onDragLeave={handleDragLeave}
      onDragOver={handleDragOver}
      ref={imageUploaderContainer}
    >
      ...
    </Box>

Answer №1

In order to prevent overlap of class names, the MUI makeStyles function generates unique classes by adding a random ID to them. For instance, it could create something like makeStyles-imageUploaderDrop-62.

While using

classList.add('imageUploaderDrop')
did apply the styles to the DOM, it didn't match the dynamic class name generated by MUI. This resulted in the styles not being visible.

To address this issue, one can access the dynamic class names directly from the useStyles() hook and manipulate them using the classList method as shown below:

const styles = useStyles();
element.classList.add(styles.imageUploaderDrop);

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

My Node.js code has encountered an unexpected end of input error

const express = require("express"); const bodyParser = require("body-parser"); const ejs = require("ejs"); const mongoose = require('mongoose'); const app = express(); app.set('view engine', 'ejs'); app.use(bodyParser.url ...

The list is failing to display

The issue encountered: Objects are not valid as a React child. If you intended to render a collection of children, consider using an array instead. Here 'res' contains nested arrays in JSON format, so I utilized _.forEach to extract it. The st ...

Connecting Jquery for dynamic table generation

I'm having trouble connecting JQuery to my file. I'm attempting to create a dynamic table to display and modify data from my database using ajax, php, and mysql. I've double-checked the code multiple times and haven't found any errors. ...

Is there a way for the active slide in keen-slider to appear larger than the rest of the slides?

I am currently using the keen-slider library for my website. All the slides have the same size except for the active one. I would like all slides to have the same size, with the exception of the active slide which should be slightly larger than the rest. ...

What is the reason behind Express serving the static file through the router, while also causing the path to the scripts folder to

Directory Layout app ├── app.js ├── public │   ├── data │   │   └── data.json │   ├── index.html │   └── js │   ├── filter-list.js └── routes └── index.js Setting up ap ...

Cracking the code of the @ symbol within this particular context

https://github.com/react-dnd/react-dnd/blob/master/examples/04%20Sortable/Simple/Card.js I'm trying to comprehend the significance of the @ symbol in this example. This is meant to be a straightforward drag and drop demonstration, but the implementa ...

What is the designated action or code in question?

let specialty = ''; function isVegetarian() { }; function isLowSodium() { }; export { specialty, isVegetarian }; export { specialty, isVegetarian }; The explanation from the editor was as follows: When exporting objects, it is done by the ...

The AudioPlayer refuses to play following a track change

I am looking to implement an audio player in React Nextjs that features interactive dots, each representing an audio track. The functionality I want is such that clicking on a dot will pause the currently playing track (if any) and start playing the select ...

Animating skill bars as you scroll down the page

How can I achieve a skill bar animation on a specific section of the page scroll? I have attempted to create a sliding skill bar animation, but it is not producing the desired effect. It currently starts animating at the beginning of the page, but I want i ...

Addressing three visual problems with an html form input, dropdown menu, and clickable button

Currently, the output of my code looks like this: https://i.stack.imgur.com/pl5CJ.jpg The first box (squared) represents an <input>, while the second box (rectangled) is a <select>. There are several issues that I am facing: The text entered ...

The modal is not displayed when the on click listener is triggered

I'm a beginner in the world of programming and I'm currently working on creating modals that pop up when clicked. However, I'm facing an issue where the pop-up message doesn't appear when I click the button. Oddly enough, only the overl ...

Click the button to increase the counter up to 2, and then decrease it back to 0 starting from 2

I'm struggling to implement this efficiently. My count keeps incrementing and decrementing by 1, causing me to get stuck at the value of 1 without going back down to zero. using react: jsfiddle The counter increases from 0 to 2 when onClick() is tri ...

How can I use JavaScript to capture the "MDCMenu:selected" event for the Menu Component in Material Design Web Components?

I am currently using the Material Design Web Components plugin known as "Menu." Once the menu is launched, my goal is to be able to effectively handle all possible ways a "menu item" can be selected. While adding an on-click event through my framework&apo ...

What is the best way to implement row ordering functionality (like row drag and drop) in the free version of the x-data-grid component from MaterialUI

I've been struggling to implement drag-and-drop functionality for my x-data-grid component to make rows orderable. The code snippet below renders rows, but they are not draggable. Here is the code that I'm having issues with. <DragDropContext ...

Implement a variety of HTTP response codes for a REST endpoint

I'm currently utilizing express to serve the REST API endpoints for a simulated backend. One of the endpoints requires the ability to return different HTTP response codes, while maintaining a 200 status for the other endpoints. Here is a snippet of my ...

utilizing angularjs and bootstrap to manage multiple button models

Recently delved into learning angularjs and bootstrap. Found a tutorial on creating buttons. <div ng-controller="ButtonsCtrl"> <h4>Checkbox</h4> <pre>{{checkModel}}</pre> <div> <button type="butto ...

Avoiding the use of numbers in v-if in Vue.js

My website features a left menu that displays different content based on the selected menu's ID. However, I currently have === 0 and === 1 in the v-if statement, and I'm looking for a way to avoid manually inputting these numbers. <template& ...

Can you explain the meaning of <!-- in javascript?

Have you ever noticed the <!-- and --> characters being used around JavaScript code like this: <script type="text/javascript"> <!-- function validateForm() { if(document.pressed == 'Submit') { ...

How can I dynamically update the URL parameter based on the selected option in a dropdown list?

There is a single select option box with three options. When a user selects an option, the corresponding value should be appended to the URL (e.g., value=needbyDate). If another option is selected later, the previous value in the URL should be replaced w ...

Enhance your web form with the Bootstrap 4 tags input feature that allows users to add tags exclusively

I'm currently utilizing Bootstrap 4 along with Bootstrap Tags Input to create a multiple category selection feature. My goal is to enable users to choose multiple items exclusively from the predefined categories listed in the predefined_list. At pres ...