Can the functions passed into Material-UI withStyles() be relocated within the component?

Attempting to break down the components of my dashboard into smaller parts has proven challenging due to their dependence on drawerWidth. Initially, I considered moving drawerWidth into the state so it can be passed down to each component. However, I encountered an issue with the variable styles, which also relies on drawerWidth. Upon reviewing material-ui documentation and reference projects, it became apparent that styles are typically located outside the class.

I made an attempt to place both variables inside the class and passed the function into withStyles through a class reference, but unfortunately, this approach failed. The page's CSS appeared distorted, and I received a warning indicating that an invalid function was passed to withStyles as shown below:

export default withStyles(DashboardLayout.styles)(DashboardLayout);

The original code snippet looks like this.

import PropTypes from 'prop-types';
import classNames from 'classnames';
import { withStyles } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';
...
// All the imported components and styles
...
export default withStyles(styles)(DashboardLayout);

The goal is to separate the drawer and appbar into their respective files without the need to hardcode drawerWidth and styles in each file.

Answer №1

To make the drawerWidth accessible to smaller components, you can define it in your custom theme as theme.drawerWidth. While official components use pre-defined theme values like palette, you have the flexibility to add new keys for your own components. Check out the theme documentation for more details.

Here's an example of creating a theme with createMuiTheme and passing it as a prop to MuiThemeProvider:

const theme = createMuiTheme({
  drawerWidth: 200 // custom key in theme object
});

function Root() {
  return (
    <MuiThemeProvider theme={theme}>
      <App/>
    </MuiThemeProvider>
  );
}

Now, you can utilize drawerWidth from the theme in smaller components using withStyles:

// Styling for your appbar
const styles = theme => ({ 
  appBar: {
    width: `calc(100% - ${theme.drawerWidth}px)`,
    marginLeft: theme.drawerWidth
  }
})
export default withStyles(styles)(YourAppBar);

// Styles for your drawer
const styles = theme => ({  
  drawer: {
    width: theme.drawerWidth,
    flexShrink: 0
  },
  drawerPaper: {
    width: theme.drawerWidth
  }
})
export default withStyles(styles)(YourDrawer);

Check out this sandbox example: https://codesandbox.io/s/7j4y8p6nox

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

Material-UI's style is taking precedence over other styles that have been defined

Introduction Last week, I posted a similar query which touched on the same issue. However, as the solution seems to be different this time around, I am revisiting it in a new thread. Check out the updated version of the CodeSanbox Example that reflects t ...

How to keep a div element fixed on the page's border vertically and horizontally adhered

Would you mind visiting the following link: and observing the layout of the page? My goal is to affix or "attach" a small div element to the right side of the page, just slightly outside of the right frame of the page. Vertically, I want this div to be ...

What is the process for embedding HTML and CSS content into an Outlook email?

Has anyone experienced trouble adding an HTML and CSS web page to an Outlook email? I attempted to use the "Insert as text" option, but the CSS file is not loading correctly in Outlook. Any suggestions on how to fix this? The error message states that the ...

bundle.js encountered a TypeError when attempting to read a property that was undefined, specifically while trying to access the PriceIndexationDataControlStandard

In the midst of developing a React component using the Microsoft PCF Framework, I encountered a perplexing error seemingly out of the blue. While making changes in TypeScript without even executing any build commands, the rendering of my component suddenly ...

React - duplicating the identical object

Recently, I embarked on a React journey and enrolled in a course to expand my knowledge. As I delve into the exercises, something caught my attention - the instructor repeatedly cloned a specific object. Curiosity piqued, I decided to investigate further. ...

Using React.js to create a search filter for users

When using useEffect with fetch(api) to set [search], I encounter an issue where "loading..." appears each time I enter something in the input box. To continue typing, I have to click on the box after every word or number. I am seeking advice on how to pr ...

Exploring Ways to Access Console.log() from Client Pages in Next.js

Struggling to debug my client-side renderings using `Console.log()` (Any tips on an easier way to use the debug tool would be appreciated), as I can only access server-rendered console logs. I'm attempting to track the flow of information for this ha ...

What is the best way to restrict the size of a table that is filled with data from a database?

Currently using a combination of React, Node, Express, and Postgres to populate a table with data retrieved from Postgres. The issue arises when the table becomes overly long, prompting the need to display only 5 rows at once while adding a scroll bar for ...

Issues encountered with certain Tailwind styles functioning improperly when deployed in a production environment with Next.js

It seems that there are some style issues occurring in the production build hosted on Netlify for a specific component. The problematic component is a wrapper located at ./layout/FormLayout.tsx. Below is the code for this wrapper: const FormLayout: React.F ...

Exploring the utilization of a constant value within a styled component

I am looking to pass a styled component to a variable and then utilize that variable in the rendering process However, I am unsure of how to go about doing this. The main reason for passing it through a variable is for conditional purposes. Sample.styled ...

React UseEffect - Triggering only when data has been updated

In my current situation, I am facing a dilemma with the useEffect hook. I need it to not run on the initial render, but only when specific data is rendered, such as home.matchsPlayed and home.winHome. This is what my code looks like: useEffect(() => ...

Using the Croppie plugin to crop an image before uploading via jQuery Ajax in PHP

I've successfully implemented a code snippet that allows image cropping using PHP, jQuery, and Ajax with the Croppie plugin. Currently, I'm facing an issue while trying to include additional input values along with the image upload process. I ...

Navigating through pages in a server component using Next.js

I am currently working on a project that involves implementing pagination using the NextJS 13 server component without relying on the use client. The goal is to ensure that when a button is clicked, new entries are added to the screen in a sequential order ...

Creating unique identifiers/primary keys for resources in react-admin: A step-by-step guide

I am working on a nextJS project that utilizes redux for state management and an admin panel called react admin. In my project, I decided to use _id instead of id as the keys. To achieve this, I followed the instructions provided in this custom identifiers ...

Display a complete calendar with the date picker on a webpage

Currently experimenting with React to build a straightforward application. Admiring the appearance of full calendars from these date pickers (once clicked): Material-UI React-Toolbox Wondering if it's feasible to present the full calendar directly ...

The module 'react-bootstrap' does not have a 'Label' export available

Attempting npm start resulted in the following error message. ./src/App.js 104:16-24 'react-bootstrap' does not contain an export named 'Label'. How can this issue be resolved? I attempted to use npm install. Is there an alternative co ...

What is the best way to prevent 2 divs from overlapping on a webpage?

I'm having trouble getting the smaller div to display right below the larger red div. I tried using the display block css property, but it doesn't seem to be working as expected. Unfortunately, I can't provide an image here, but you can vie ...

The website's navigation system effectively directs content within the initial 100% viewport

I have encountered a slight issue. I created a Sidebar Navigation with some added "hey's" to demonstrate the problem: * { margin: 0; padding: 0; font-family: 'Roboto', sans-serif; } nav { height: 100vh; width: 250px; borde ...

Struggling to figure out how to make this Vue function work

I am working with a list of tasks, where each task is contained within a div element. I am looking to create a function that changes the border color of a task to red when clicked, and reverts the previous task's border to normal. I have two files: &a ...

Issue with displaying background image in h2 element

Consider me a novice who learns primarily through trial and error. Unfortunately, I'm stuck on this particular issue. My goal is to have an image appear behind the h2 text on my homepage, but despite my efforts, I can't seem to make it work. You ...