The universal CSS variables of Material UI

Creating reusable CSS variables for components can greatly simplify styling. In regular CSS, you would declare them like this:

:root {
  --box-shadow: 0 2px 5px -1px rgba(0, 0, 0, 0.3);
}

This variable can then be utilized as shown below:

.my-class {
  box-shadow: var(--box-shadow);
}

The challenge arises when trying to achieve the same using useStyles. The attempted method is as follows:

const theme = createMuiTheme({
  shadowing: {
    boxShadow: "0 2px 5px -1px rgba(0, 0, 0, 0.3)",
  }
});

The main App should be wrapped within:

<ThemeProvider theme={theme}>
  <App />
</ThemeProvider>

To use it in a component, an approach similar to the below was tried:

const useStyles = makeStyles(theme => ({
  workImage: {
    boxShadow: theme.shadowing,
  },
}));

However, it seems to not be functioning as intended.

Answer №1

For my unique situation, I found it necessary to utilize both createMuiTheme and custom variables. Here is the approach I took:

Firstly, I initialized a theme using createMuiTheme

const theme = createMuiTheme({
  typography: {
    fontFamily: "verdana",
  },
});

Next, I created a separate object where I defined my variables:

const cssVariables = {
  shadowing: {
     boxShadow: "0 2px 5px -1px rgba(0, 0, 0, 0.3)",
  }
};

Then, I passed both objects to my ThemeProvider:

<ThemeProvider theme={{ ...theme, ...cssVariables }}>

Finally, to access the variable within my styles:

const useStyles = makeStyles(theme => ({
  workImage: {
    boxShadow: theme.shadowing.boxShadow,
  },
}));

Answer №2

The function "createMuiTheme" only accepts an object with a specified set of keys such as palette, Typography, spacing, etc.

You don't need to use any special format for the object.

const customTheme = {
  shadowing: {
     boxShadow: "0 2px 5px -1px rgba(0, 0, 0, 0.3)",
  }
};

Answer №3

To accomplish this, I declared a constant in JavaScript with the desired value and then assigned it to the CSS property:

const textColor = "purple";

    const classes = useStyles(theme =>
        createStyles({
            root: {
            color: textColor
            }
}));

Answer №4

The latest version of Material UI (v5.6.0) introduces a new feature that allows the use of CSS variables, although it is still considered experimental (learn more).

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

Can you retrieve the second value using JSON.stringify?

Currently implementing JSON.stringify(data.message) which returns the following value: [ { "code":"PasswordTooShort", "description":"Passwords must be at least 6 characters." } ] I aim to extract the description value for my alert message ...

Dealing with a Nodejs/Express and Angular project - Handling the 404 error

Recently, I decided to dive into learning the MEAN stack and thought it would be a great idea to test my skills by building an application. My goal was simple: display a static variable ('hello') using Angular in the HTML. However, I ran into an ...

Explore interactive hover effects with jQuery and UI for a dynamic user experience!

Is it possible to initiate dragging on mouseover instead of click? Imagine a div that instantly starts dragging when hovered over. How can this be achieved? I would appreciate any guidance on how to make this happen. Thank you ...

Choosing and aiming with jQuery on dynamically created Ajax pages

I am facing an issue with a Select box on a page that is generated through AJAX. Here is the code snippet: <select onchange="setLocation(this.value)"> <option value="https://xy.com/accessories.html?dir=asc&amp;limit=15&amp;order=name"& ...

Shifting the key of a choropleth map with R, rMaps, and datamaps

My challenge is to center the legend below a choropleth map of the United States. I don't have much experience with JS or CSS, but I decided to delve into the datamaps.all.min.js file in the R-3.2.1\library\rMaps\libraries\datamaps ...

The global variable remains unchanged after the Ajax request is made

I am attempting to utilize AJAX in JavaScript to retrieve two values, use them for calculations globally, and then display the final result. Below are my code snippets. // My calculation functions will be implemented here var value1 = 0; var v ...

The React component in Microsoft Graph Toolkit is failing to update when the state of its props changes

I have been experimenting with the Microsoft Graph Toolkit React component by implementing templates as outlined here. I passed a react state as props to the component and noticed that the component does not re-render when the state changes, unlike a regul ...

What is the best way to display data in a React application depending on a boolean value?

Being new to React and JavaScript, I am currently struggling with boolean logic. I have a function called Profile which includes two constant methods that each return different data. function Profile(props) { const returnNormalProfile() const return ...

Failed request using Ajax

I've been trying to call a C# function using ajax, but for some reason it's not working. Here is the ajax call I'm making: $('#button1 button').click(function () { var username = "username_declared"; var firstname = "firs ...

Organization and Naming Standards for Projects

After exploring the Repeating module name for each module component issue, we have decided to adopt the organizational recommendations outlined in the Best Practice Recommendations for Angular App Structure blog post. This approach has been implemented in ...

Providing a user with a special discount tailored to their email address?

<script type="text/javascript"> function updatePrice() { var price = document.getElementById("product").value; var size_price = document.getElementById("size").value; var a=parseInt(price);//parsed type price var b=parseInt(size_price);//pa ...

Utilize Bootstrap's form-inline feature to arrange fields side by side in one neat

I am looking to customize my sign-in form layout by displaying the fields in a row next to each other rather than under each other. header: Update: I have successfully implemented this code <header class="navbar navbar-fixed-top navbar-inverse"> & ...

What is the reason behind the inability to overflow the Safari viewport?

My website, , has a footer that is clickable in Chrome but not in Safari. When users scroll to the footer in Safari, the screen jumps back to the top, making it inaccessible. Can anyone help me identify the issue? Below is the CSS code for my React projec ...

Limit a div to only accept a specific stylesheet

Currently, I am immersed in a project that involves HTML5, MVC 4, CSS 3, JQuery, and LINQ. We have meticulously designed styles for various ui, li, and other html controls within the project. However, I now face the challenge of integrating a JQ Grid (htt ...

Intersecting table columns with a different data table

My task is to create a table with a column that contains another table, where I want the colors of each alternating row to be different. Please refer to the image below (ignore the "CharacterAgain" column). Below is an example of AngularJS code for the ta ...

Issue: Infinite loops detected in AJAX functions

I am using $.get methods in the following code snippet: $.get("/url" , function(z) { var a = $(z).find("span"); for (var i = 0 ; i<a.length; i++){ var v = $(a).eq(i).children("strong:first").text(); alert(v); } }); However, the s ...

Change the font style of individual characters within a string using CSS or JavaScript, instead of applying it to the entire

Is it feasible to assign a specific font to a particular character? I would like: #test_id{ font-family: "digitalfont"; font-family-of-, : "HelveticaNeue-Light"; } In order to set a font for a comma and a separate font for the rest, do I need to ...

Guidelines for utilizing React to select parameters in an Axios request

As a newcomer to ReactJs, I am working with a Product table on MySQL. I have successfully developed a dynamic table in the front-end using ReactJS along with MySQL and NodeJs on the backend. The dynamic table consists of four columns: Product, Quantity, Pr ...

Incorporate a dynamic PowerPoint presentation directly onto my website

In my situation, on the client side, users can select image files (jpg|png|gif), PDF files, and PPT files which are then stored in a database. When viewing these selected files in the admin panel, I am using conditional statements to display them appropr ...

Restricting zooming to only occur within the img element in a UI

Is there a method to enable image zoom inside specific divs without affecting the overall page zoom? At the moment, I have: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale ...