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);

https://i.sstatic.net/lz1m7.png 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);

https://i.sstatic.net/jlr5X.png

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

Updating Icons for Individual Rows in React Data Grid

Currently, I'm working on developing an SFTP file uploader application. This small app facilitates the transfer of files to and from S3 using MUI DATAGRID. While the functionality works as expected - allowing me to download/upload files with a click ...

Make sure to incorporate certain node_modules folders within Babel 7

My issue involves a dependency located in the node_modules directory that requires compilation through Babel. Despite upgrading my stack, I am unable to get Babel to compile the dependency. Current versions: @babel/core 7.5.4 webpack 2.7.0 Here is my w ...

When the progress bar is clicked, the background color changes and then changes back again

https://www.w3schools.com/code/tryit.asp?filename=FG1ZE0NJ4ZX7 https://i.stack.imgur.com/Bnd0k.png I have created a progress bar that resembles the screenshot provided. When I hover over it, the color changes to green. However, I am looking for assistanc ...

Integrating FCM with NextJs for enhanced push notification

I'm facing an issue while trying to integrate FCM with next.js. The error message states that there is a problem with registering the default service worker. Can anyone provide assistance regarding the next.config.js file? Encountered FirebaseError: M ...

Attempting to display items using the map method, pulling in text from an array

I am working with an array state that tracks the text entered by the user in a text field. My goal is to display this text within a component so users can see what they have previously entered. However, I am facing an issue with my Hashtags component when ...

Encountering difficulties while importing a component with material-ui through webpack module federation

In this demonstration, we are utilizing a React app called host_ui as the host and material_components as a remote module. The material_ui module provides a component named NavBar. import React from 'react'; import AppBar from '@material-ui/ ...

Looking to incorporate content from an external website onto my own site

I have experimented with various types of HTML tags such as iframe, embed, and object to display external websites. Some of them load successfully, while others do not. After researching my issue on Google, I discovered that "For security reasons, some si ...

What consequences can arise from sticking with Material-UI version 0.20.1?

Utilizing Material-UI 0.18.7 for our frontend has become outdated, and upgrading to a 3.x release would require a significant rewrite according to our frontend developer. Due to the size and complexity of our frontend, we are not in a position to tackle ...

What is the optimal amount of static HTML to include in React website?

How should I structure my React app to handle both static and dynamic content? (I am a newcomer to React.) I have developed a single page application with the following basic layout: <body> <div id="container"> <div id="header"> ...

"Utilizing the usePrevious hook in React: A step-by-step

After referencing the React documentation, it seems like I may not be using this code correctly. import { useEffect, useRef } from 'react'; export default function usePreviousState(state) { const ref = useRef(); useEffect(() => { ref ...

Improving code efficiency for checkboxes in upcoming TypeScript versions

Is it possible to create a single checkbox component and dynamically pass different values to it without repeating code? I have set up these checkboxes to help me check the maximum and minimum values of some API data. const[checkValMax, setCheckValMax]= u ...

Is there a way to target the mat-icon element using the icon's name in CSS

I have a group of mat-icons that are automatically generated, meaning I cannot assign them ids or classes. The only way to distinguish between them is by their names: <mat-icon role="img">details</mat-icon> <mat-icon role="img ...

Enhance the aesthetics of material-ui tooltips by utilizing @emotion/styled

Can material-ui tooltips be customized using the styled function from @emotion/styled? import { Tooltip } from '@material-ui/core'; import styled from '@emotion/styled'; const MyTooltip = styled(Tooltip)` // customize the tooltip ...

Encountering error in Xcode Archive command when using Ionic Capacitor with React - Command PhaseScriptExecution terminated with a non-zero exit code

After a few days of running the Xcode publishing phase without making any changes to the project, I consistently encounter this error. Oddly enough, when other developers run the code on their computers, they don't face the same issue. Here is the er ...

How to customize a disabled paper-input element in Polymer 1.0?

Help with Polymer 1.0: I've encountered an issue where setting a paper-input element to 'disabled' results in very light gray text and underline, making it hard to read. I've been trying to use CSS to change the text color but haven&ap ...

Can you explain the functionality of the const handleChange = (prop) => (event) => {} function and its significance?

While going through the documentation for MUI, I stumbled upon a new syntax for arrow functions in JavaScript that I haven't seen before. I tried to figure out how it works but couldn't find any information on it. The syntax looks like this: con ...

Enhance Component Reusability in React by Utilizing Typescript

As I embark on developing a React application, my primary goal is to keep my code DRY. This project marks my first experience with Typescript, and I am grappling with the challenge of ensuring reusability in my components where JSX remains consistent acros ...

Encountering an error while attempting to import the JSON Web Token module from 'jsonwebtoken'

Whenever I attempt to import jwt from jsonwebtoken in my React app, I encounter the following error: ERROR in ./node_modules/jsonwebtoken/sign.js 18:4-21 Module not found: Error: Can't resolve 'crypto' in 'C:\Users\swami& ...

The width of each column in this dataset is variable and unknown

I need to organize a varying number of items into columns. The sizes of both the items and container are unknown, as well as how many columns will fit or what width they should be. I want the browser to arrange the items in as many columns as possible with ...

What is the best way to prevent numbers (even in String format) in a MaterialUI TextField?

Check out the following code snippet: <Grid item lg={6} md={6} xs={12} > <TextField fullWidth type={'text'} label="Product Color" value={productColor} onChange={(e) => setProductColor(e.target.value)} /> </Grid> ...