Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Material UI (withStyle) style on an external file in React?

I'm trying to put all my styles in an external file to be cleaner but i can't find the solution to do it.

For exemple, i've got something like this:

  const styles = theme => ({
    appBar: {
      zIndex: theme.zIndex.drawer + 1,
      position: 'absolute',
      marginLeft: drawerWidth,
      width: '100%',
    },
  });

with this at the end of my App component:

App.propTypes = {
  classes: PropTypes.object.isRequired,
  theme: PropTypes.object.isRequired,
};

export default withStyles(styles, { withTheme: true })(App);

But if i'm trying to put my style outside of my component and import it, I can't access to theme.zIndex.drawer

My external style file is looking like this:

const drawerWidth = 240;

export default {
  appBar: {
    zIndex: theme.zIndex.drawer + 1,
    position: 'absolute',
    marginLeft: drawerWidth,
    width: '100%',
  },
}

I don't understand very well how it works, does someone can help me ?

like image 322
tinmarfrutos Avatar asked Aug 07 '18 14:08

tinmarfrutos


People also ask

How do you apply styles in material UI?

Luckily, Material-UI provides a solution for this: makeStyles . Using makeStyles , you can add CSS in JS without making your code look messy. First, you need to import makeStyles in your app. Next, pass all the CSS you need in your app as an object to makeStyles and store it inside a variable, useStyles .

How do I pass props to MUI styles?

To pass props to React Material UI styles, we can call the useStyle hook returned by makeStyles with the props object. In makeStyles , we can set the style properties that takes the props as a parameter and return the value we want.


Video Answer


1 Answers

When the style was within the App.jsx, is was a function, when you moved it to a seperate file, you made it an object.

You need to export a function, not a JSON object:

const drawerWidth = 240;

export default theme => ({
  appBar: {
    zIndex: theme.zIndex.drawer + 1,
    position: 'absolute',
    marginLeft: drawerWidth,
    width: '100%',
  },
})
like image 149
Anas Avatar answered Oct 17 '22 22:10

Anas