Is it possible to include pseudo element elements in the configuration of a custom theme in Material UI?

Within my file themeConfig.js, I have defined several theme variables that are utilized to style different components throughout my application. Among these variables, there is a need for implementing the -webkit scrollbar styles for certain components. Due to the length and bulkiness of the -webkit styles, I am interested in incorporating them directly into my themeConfig.js file. These scrollbar styles involve pseudo-elements, and while they can be assigned, I am encountering difficulties in applying them within themeConfig.js.

themeConfig.js

const myTheme = createMuiTheme({
  layout: {
    header: 64,
    sideNav: 45,
    mainDivHeight: 250,
    ...
  }
})

export default myTheme

ComponentExample.js

import { makeStyles } from '@material-ui/core'

const ComponentExample = () => {
  const classes = useStyles()

  return (
    <div className={classes.mainDiv}>I'm a div</div>
  )
}

const useStyles = makeStyles(theme => ({
  mainDiv: {
    height: theme.layout.mainDivHeight,
    overflowY: 'scroll',
    '&::-webkit-scrollbar': {
      width: 8,
    },
    '&::-webkit-scrollbar-track': {
      boxShadow: 'inset 0 0 6px rgba(0,0,0,0.00)',
      webkitBoxShadow: 'inset 0 0 6px rgba(0,0,0,0.00)',
    },
    '&::-webkit-scrollbar-thumb': {
      backgroundColor: 'rgba(0,0,0,.2)',
      outline: '1px solid slategrey',
      borderRadius: 7,
    },
  }
}))

export default ComponentExample

I am looking for a way to encapsulate this code snippet as a variable in my theme file and apply it to components:

    overflowY: 'scroll',
    '&::-webkit-scrollbar': {
      width: 8,
    },
    '&::-webkit-scrollbar-track': {
      boxShadow: 'inset 0 0 6px rgba(0,0,0,0.00)',
      webkitBoxShadow: 'inset 0 0 6px rgba(0,0,0,0.00)',
    },
    '&::-webkit-scrollbar-thumb': {
      backgroundColor: 'rgba(0,0,0,.2)',
      outline: '1px solid slategrey',
      borderRadius: 7,
    },

However, the method in which theme styles are defined in makeStyles involves a one-to-one property assignment, leaving me unsure about how to efficiently apply an entire style object like this to a component. Any guidance on this matter would be greatly appreciated!

Answer №1

The styles defined within the makeStyles function are contained in an object that can be created using various methods supported by JavaScript. One approach to managing this is to organize the desired styles in a single object within the theme (as shown below with scrollbarStyles) and use the object spread syntax where you intend to apply them in the makeStyles function.

See the following functional example:

import React from "react";
import {
  createMuiTheme,
  ThemeProvider,
  makeStyles
} from "@material-ui/core/styles";

const myTheme = createMuiTheme({
  layout: {
    header: 64,
    sideNav: 45,
    mainDivHeight: 250,
    scrollbarStyles: {
      overflowY: "scroll",
      "&::-webkit-scrollbar": {
        width: 8
      },
      "&::-webkit-scrollbar-track": {
        boxShadow: "inset 0 0 6px rgba(0,0,0,0.00)",
        webkitBoxShadow: "inset 0 0 6px rgba(0,0,0,0.00)"
      },
      "&::-webkit-scrollbar-thumb": {
        backgroundColor: "rgba(0,0,0,.2)",
        outline: "1px solid slategrey",
        borderRadius: 7
      }
    }
  }
});

const useStyles = makeStyles(theme => ({
  mainDiv: {
    ...theme.layout.scrollbarStyles,
    height: theme.layout.mainDivHeight
  }
}));
function ComponentExample() {
  const classes = useStyles();

  return (
    <div className={classes.mainDiv}>
      <div style={{ margin: "50px" }}>
        I'm a div with enough content to make me scroll
      </div>
      <div style={{ margin: "50px" }}>
        I'm a div with enough content to make me scroll
      </div>
      <div style={{ margin: "50px" }}>
        I'm a div with enough content to make me scroll
      </div>
      <div style={{ margin: "50px" }}>
        I'm a div with enough content to make me scroll
      </div>
      <div style={{ margin: "50px" }}>
        I'm a div with enough content to make me scroll
      </div>
    </div>
  );
}
export default function App() {
  return (
    <ThemeProvider theme={myTheme}>
      <ComponentExample />
    </ThemeProvider>
  );
}

https://codesandbox.io/s/scrollbar-styles-in-theme-q923q?fontsize=14&hidenavigation=1&theme=dark

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

I am looking to integrate a custom button that, when clicked, will launch the file explorer for me to choose a file. Once selected, the file name should automatically populate in the input field

In the code below, when the button is clicked, Windows Explorer should open and allow the user to select a file. The selected file should then be displayed in the input field. The file type should not be 'File'. <Grid.Column width={8}> ...

Is there a way to personalize the title and text of a tooltip within Apexchart?

I am working on creating a scatter plot using Apexchart to demonstrate the correlation between two sets of data. I want to personalize the tooltip in the chart by adding a distinct title for each pair of x and y values. Here is my current JSX setup, where ...

Determine if an element from the first array is present in the second array

I've encountered a challenge while building a simple react app and I could use some help. The Problem at Hand :- My goal is to compare items in firstArray (which contains separate dictionaries) with those in secondArray. While the loop for checking ...

"Ensuring Username Uniqueness in AngularJS and CakePHP3: A Step-by-Step

<input type="email" id="username" dbrans-validate-async="{unique: isUsernameUnique}" ng-model="username" required class="form-control" name="username"> $scope.isUsernameUnique = function(username) { $http.get(url+'/isUsernameUnique&apo ...

One way to assign the starting value of a select element in React

I have a straightforward application that showcases data, with the state changing based on a select input. However, I am looking to set the default select option to United Kingdom instead of Afghanistan, which is currently the default due to alphabetical o ...

Utilizing window.matchMedia in Javascript to retain user selections during page transitions

I am encountering difficulties with the prefers-color-scheme feature and the logic I am attempting to implement. Specifically, I have a toggle on my website that allows users to override their preferred color scheme (black or light mode). However, I am fac ...

All web resources need to be included in the web_accessible_resources manifest key

I'm encountering an issue with my Angular app. The error message on the client console reads: Denying load of chrome-extension://fiekimdgbphfmnlbiahcfdgcipcopmep/js/lib/angular/angular.min.js.map. Resources must be listed in the web_accessible_resour ...

"Utilizing Material-UI in React to create a textfield input with number validation

I am currently working on an input field that should only accept values within a specified range of min and max. However, I have encountered an issue where manually entering a number bypasses this control mechanism. Is there a way to prevent this from happ ...

Using react-hook-form to easily update form data

While working on my project with react-hook-form for updating and creating details, I encountered a problem specifically in the update form. The values were not updating properly as expected. The issue seems to be within the file countryupdate.tsx. import ...

Enabling and Disabling Input Fields Based on Selections in VueJS

Originally submitted on es.stackoverflow.com by José: I came across an example in JavaScript that works, but I'm struggling to implement it in vue.js. I've been attempting it for some time without success. Apologies for any inconvenience. < ...

Experience the full functionality of Google Maps API without the need for jQuery or PHP with PanTo

I'm not a developer and I find myself stuck in the panTo() function. All I want is to execute this function with an if-else statement without having to reload the Google Map or using jQuery. <body> <div id="map"></div> <d ...

Displaying an image with a JavaScript variable is a common task in web

I have a Javascript code snippet below where the image name "samson decosta" is stored in a MySQL database. I am retrieving this image and trying to display it as a background_image in a div. document.getElementById("image_chk").style.backgroundImage="url ...

Issues with date clicking on FullCalendar in Angular

I'm currently using version 4.4.0 of the FullCalendar plugin, but I am facing an issue where the dayClick event is not being triggered in my code. Below is a snippet of my code: calendar.component.html <full-calendar defaultView="dayGridMonth ...

How to easily center text across multiple lines using CSS

Looking for a way to center text horizontally and vertically within a div? I had it all working perfectly with this code snippet from a Stack Overflow post: text-align: center; vertical-align: middle; line-height: 90px; /* set line height to match you ...

Storing the API key returned by the Node.js store as a variable was

Just starting out with node and experimenting with A node.js library for the Pardot API I provide my userKey, email, and password to pardot, which returns an api_key. This is the code snippet I am using for authentication. Upon running my node server, I ...

Troubleshooting issue with SQL delete statement - unable to delete a recipe with the specified recipe_id

Developing a functionality to delete data. I am currently working on removing a particular recipe by its unique identifier, which is the recipe_id. The issue I encountered is that when I send the request to delete using the handleDelete function in my bac ...

Ways to broaden the map of a variable in SCSS

Currently, I am utilizing a package known as Buefy, which acts as a Vue.js wrapper for the Bulma CSS framework library. Within Buefy's template components, there is an attribute/property called type (e.g., type="is-warning"). According to the document ...

SVG path with dynamic elements

Consider the following SVG: <svg xmlns="http://www.w3.org/2000/svg" width="237" height="129" viewBox="0 0 237 129" fill="none"> <path d="M228 1H9C4.58172 1 1 4.58172 1 9V91V104V127L20 111.483L228 112C232.4 ...

Tips for maintaining a loading screen for longer than 4 seconds?

I want to maintain the loading screen for a minimum of 4 seconds. However, the timer at the end does not seem to be functioning as expected. Here is the code snippet I am using: window.addEventListener("load", () => { const preload = document.querySe ...

Applying Styles to Cells Using the Google Sheets API (v4)

Having encountered an issue while using the Google Sheets API (v4) for programmatically creating or updating spreadsheets, I have come across the following problem: According to the documentation (https://developers.google.com/sheets/api/reference/rest/v4 ...