MUI Drawer set background color - javascript

How to simply set background color of MUI Drawer?
tried this, but doesn't work
<Drawer
style={listStyle3}
open={this.state.menuOpened}
docked={false}
onRequestChange={(menuOpened) => this.setState({menuOpened})}
/>
const listStyle3 = {
background: '#fafa00',
backgroundColor: 'red'
}

Edit: (May-21) - Material UI V4.11.1
This can be done differently in version 4.11.1 and functional components.
There's no need to use an HoC anymore. Here's how it's done:
You should use the makeStyles helper to create the hook with a definitions of the classes and use the hook to pull them out.
const useStyles = makeStyles({
list: {
width: 250
},
fullList: {
width: "auto"
},
paper: {
background: "blue"
}
});
const DrawerWrapper = () => {
const classes = useStyles();
return (
<Drawer
classes={{ paper: classes.paper }}
open={isOpen}
onClose={() => setIsOpen(false)}
>
<div
tabIndex={0}
role="button"
onClick={() => setIsOpen(true)}
classes={{ root: classes.root }}
>
{sideList}
</div>
</Drawer>
)
}
Here's a working sandbox
Edit: (Jan-19) - Material UI V3.8.3
As for the latest version asked, the way to configure the backgroundColor would be by overriding the classes.
Based on material-ui documentation here, and the css api for drawer here - This can be done by creating an object in the form of:
const styles = {
paper: {
background: "blue"
}
}
and passing it to the Drawer component:
<Drawer
classes={{ paper: classes.paper }}
open={this.state.left}
onClose={this.toggleDrawer("left", false)}
>
A working example can be seen in this codesandbox.
Don't forget to wrap your component with material-ui's withStyles HoC as mentioned here
Based on the props you used I have the reason to think that you're using a version which is lower than v1.3.1 (the last stable version) but for the next questions you'll ask, I recommend writing the version you're using.
For version lower than V1, you can change the containerStyle prop like this:
<Drawer open={true} containerStyle={{backgroundColor: 'black'}}/>

In MUI v5, you can use the sx prop to style MUI components:
<Drawer
PaperProps={{
sx: {
backgroundColor: "pink",
color: "red",
}
}}
Or use styleOverrides to define the custom styles in createTheme:
const theme = createTheme({
components: {
MuiDrawer: {
styleOverrides: {
paper: {
backgroundColor: "pink",
color: "red",
}
}
}
}
});

Material UI V4.3.2
As in this version you can change the backgroundColor by making use of makeStyles from '#material-ui/core/styles' as shown below:
import Drawer from '#material-ui/core/Drawer';
import { makeStyles } from '#material-ui/core/styles';
const useStyles = makeStyles({
paper: {
background: 'black',
color: 'white'
}
});
const SideDrawer = props => {
const styles = useStyles();
return (
<Drawer
anchor="right"
open={props.drawerOpen}
onClose={() => props.toggleDrawer(false)}
classes={{ paper: styles.paper }}
>
Items
</Drawer>
);
};
export default SideDrawer;

Drawer doesn't accept style props. Use classes instead
See Drawer API

If anyone's looking for how to do this conditionally for dark/light mode, you can make 2 separate classes and use a conditional to use the right one in the component. Here's an example of how to modify #Yirenkyi's answer do achieve this:
import Drawer from '#material-ui/core/Drawer';
import { makeStyles } from '#material-ui/core/styles';
const useStyles = makeStyles({
paperLight: {
background: 'white',
color: 'black'
},
paperDark: {
background: 'black',
color: 'white'
}
});
const SideDrawer = props => {
const userPrefersDarkMode = true; //here's your condition
const styles = useStyles();
return (
<Drawer
anchor="right"
open={props.drawerOpen}
onClose={() => props.toggleDrawer(false)}
classes={{ paper: userPrefersDarkMode ? styles.paperDark : styles.paperLight }}
>
Items
</Drawer>
);
};
export default SideDrawer;

Related

Material UI's Stepper StepLabel Icon issue with undefined

just having issues with trying to implememnt a custom Step Label Icon within the nodes of the Stepper Component provided by Material UI. I am trying to implement an icon within each circle, as seen here from Material UI's demo
however, am coming across an error
Please see my code below. Thanks!
import React from 'react';
import { Typography } from '#material-ui/core';
import { withStyles, styles } from '#material-ui/core/styles';
const styles = theme => ({
checklistHeader: {
fontWeight: 'bold',
marginTop: '80px',
color: 'white'
},
connectorIcon: {
color: theme.palette.text.secondary
},
active: {
backgroundColor: 'green'
}
});
const steps = ['Select campaign settings', 'Select campaign settings', 'Select campaign settings'];
const ColorlibStepIconRoot = styled('div')(({ theme, ownerState }) => ({
backgroundColor: theme.palette.mode === 'dark' ? theme.palette.grey[700] : '#ccc',
zIndex: 1,
color: '#fff',
width: 50,
height: 50,
display: 'flex',
borderRadius: '50%',
justifyContent: 'center',
alignItems: 'center',
...(ownerState.active && {
backgroundImage:
'linear-gradient( 136deg, rgb(242,113,33) 0%, rgb(233,64,87) 50%, rgb(138,35,135) 100%)',
boxShadow: '0 4px 10px 0 rgba(0,0,0,.25)',
}),
...(ownerState.completed && {
backgroundImage:
'linear-gradient( 136deg, rgb(242,113,33) 0%, rgb(233,64,87) 50%, rgb(138,35,135) 100%)',
}),
}));
const ColorlibStepIcon = ({
icon, active, completed, className
}) => {
const icons = {
1: <Icon style={{ color: 'red' }}>create_outline</Icon>,
2: <Icon style={{ color: 'red' }}>star</Icon>,
3: <Icon style={{ color: 'red' }}>people</Icon>,
};
return (
<ColorlibStepIconRoot ownerState={{ completed, active }} className={className}>
{icons[String(icon)]}
</ColorlibStepIconRoot>
);
};
const Stepper = ({ classes }) => {
return (
<React.Fragment>
<Typography variant="h6" align="center" gutterBottom className={classes.checklistHeader}>Please complete the following criterion</Typography>
<Stepper alternativeLabel activeStep={2} style={{ background: 'none' }}>
{steps.map(label => (
<Step key={label}>
<StepLabel StepIconComponent={ColorlibStepIcon}>{label}</StepLabel>
</Step>
))}
</Stepper>
</React.Fragment>
);
};
Stepper.defaultProps = {
};
Stepper.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles(styles, { withTheme: true })(Stepper);
It seems like the styled component is undefined. Is there any way that I can bypass this
The styled() function is only available in v5. You either need to upgrade to MUI v5 using this installation guide or use the older API in v4, (The equivalent is withStyles):
V5
import { styled } from '#mui/material/styles';
const StyledComponent = styled(Component)({
// your styles
});
V4
import { withStyles, styles } from '#material-ui/core/styles';
const StyledComponent = withStyles({
// your styles
})(Component);
You can see the v4 docs here and the v5 docs here.

What is the alternative of makeStyles for Material UI v.5

I just started using Material UI version 5. Originally to use my custom theme's styles, I would use makestyles, but it seems that does not work in v.5. My themes are on their own component, and to import those, I used {createTheme} instead of the old {createMuiTheme}. I have my theme imported into the Parent component as usual and have it set up as <ThemeProvider theme{theme}></ThemeProvider>.
Now, on my other component, I again was trying to use useStyles, but it was not working because it is not used in version 5. I am having a hard time trying to figure out how to convert it so that it can be used in version 5. Here is some of the unfinished code I was working on:
const useStyles = makeStyles((theme) => ({
logo: {
height: "8em",
marginLeft: "0.2em",
},
tabContainer: {
marginLeft: "auto",
},
tab: {
...theme.typography.tab,
minWidth: 10,
marginRight: "50px",
opacity: 1,
"&hover": {
color: theme.palette.common.purple,
textDecoration:"none",
},
},
}));
export default function Navigation(props) {
const classes = useStyles();
const [value, setValue] = useState(0);
const handleChange = (e, value) => {
setValue(value);
};
const refreshPage = () => {
window.location.reload();
};
useEffect(() => {
switch (window.location.pathname) {
case "/":
if (value !== 0) {
setValue(0);
}
break;
default:
break;
}
}, [value]);
return (
<React.Fragment>
<ElevationScroll>
<AppBar
position="relative"
style={{
borderBottom: "2px solid black",
}}
>
<Toolbar disableGutters>
<img src={logo} alt="nasa logo" className={classes.logo}/>
<Typography variant="h1" style={{ textAlign: "center" }}>
Nasa<br></br>Photos
</Typography>
<Tabs
value={value}
onChange={handleChange}
className={classes.tabContainer}
indicatorColor="primary"
>
<Tab
className={classes.tab}
component={Link}
onClick={refreshPage}
to="/"
label="Home"
/>
</Tabs>
</Toolbar>
</AppBar>
</ElevationScroll>
</React.Fragment>
);
}
I have read about the xs property and I have also heard of the styled() through Material UI's documentation, but I am having a hard time applying it to the code that I have written and would like a push in the right direction.
So to edit what I had earlier, I am going to also add my Theme.js file as well. I thought that this has been done correctly, but again it isn't reading my tab nor my palette.
import {createTheme} from "#mui/material/styles";
const pink = "#FFC0CB";
const lightblue = "#ADD8E6";
const purple = "#800080";
const black = "#000000";
const theme = createTheme({
palette: {
common: {
pink: pink,
lightblue: lightblue,
purple: purple,
black: black
},
primary: {
main: pink,
mainGradient: "linear-gradient(to left, purple, pink)",
},
secondary: {
main: lightblue,
mainGradient: "linear-gradient(to right, lightblue, pink)"
},
},
typography: {
tab: {
fontFamily:"Orbitron",
textTransform: "none",
fontSize: "2.5rem",
color: black,
},
h1: {
fontFamily: "Orbitron",
fontSize: "2.5em"
},
h2: {
fontFamily: "Orbitron",
fontSize: "2.5em"
},
subtitle1: {
fontFamily: "Orbitron"
},
subtitle2: {
fontFamily: "Orbitron",
fontSize: "1.5rem"
},
buttons: {
fontFamily: "Orbitron",
textTransform: "none"
},
},
});
export default theme
I have imported my theme into my App.js file which is my top level file, I will include that here just in case something has been done wrong with that:
import React,{useState} from "react";
import PicOfDay from "./Components/PictureOfDay";
import Navigation from "./Components/Navigation";
import {
Typography,
} from "#mui/material";
import {ThemeProvider} from '#mui/material/styles'
import theme from "../src/ui/Theme";
import {BrowserRouter as Router} from "react-router-dom";
function App(props) {
const [date, setDate] = useState(new Date());
return (
<ThemeProvider theme={theme}>
<Router>
<Navigation date={date} setDate={setDate} />
<Typography
variant="h1"
style={{fontSize: "5rem", textAlign: "center", marginTop:"2rem"}}
>
Astronomy Picture of the Day
</Typography>
{/* <PicOfDay date={date} /> */}
</Router>
</ThemeProvider>
);
}
export default App;
I did look at some documentation a couple of you sent me, and I was looking at the troubleshooting part where it said "[Types] Property "palette", "spacing" does not exist on type 'DefaultTheme'" because makeStyles is exported differently and it does not know about Theme. There seems to be a snipet to put in a typescript project (which I am not running, I am using javascript) and there was a section to add a ts file to my javascript and put the snippet it recommended, which I tried, but am I missing something because it did not do anything and I am not sure if I need to put something in my App.js file in order for it to read that?
You can still use the makeStyles utils as what you're using, but in material v5 if you love to do it you need to install one more package #mui/styles and
import { makeStyles } from '#mui/styles';
https://mui.com/guides/migration-v4/#mui-material-styles
The makeStyles JSS utility is no longer exported from #mui/material/styles. You can use #mui/styles/makeStyles instead.
Also, you need to add tab and purple to createTheme if you need them
const theme = createTheme({
typography: {
tab: {
fontSize: 20,
},
},
palette: {
common: {
purple: 'purple',
},
},
})
Based on documentation:
#mui/styles is the legacy styling solution for MUI. It is deprecated in v5. It depends on JSS as a styling solution, which is not used in the #mui/material anymore.
You can use the-sx-prop or styled
so what i understood from this question is that you want to add custom classes to the material-ui components. and makestyles is giving you error about theme.. you can resolve this by providing default theme to makestyles. you can use ThemeProvider to do that.. all you've to do is create a default theme with createTheme() then use that in ThemeProvider to pass it to all components in tree below ThemeProvider.. just use ThemeProvider to wrap your root component and that will provide default theme to each makeStyles that are currently in use..
import { makeStyles } from '#mui/styles';
import { createTheme, ThemeProvider } from '#mui/material/styles';
const theme = createTheme();
const useStyles = makeStyles((theme) => (
root : {
background: theme.palette.primary.main,
}));
function Component() {
const classes = useStyles();
return <div className={classes.root} />
}
// In the root of your app
function App(props) {
return <ThemeProvider theme={theme}><Component {...props} /></ThemeProvider>;
}
import * as React from 'react';
import { StyledEngineProvider } from '#mui/material/styles';
export default function GlobalCssPriority() {
return (
<StyledEngineProvider injectFirst>
{/* Your component tree. Now you can override MUI's styles. */}
</StyledEngineProvider>
);
}
You need to use provider on main file to get default styles first.
Visit here Material UI injections!

How to use multiple styles in material ui withStyles() React JS?

I have the following:
const styles = theme => ({root: {backgroundColor: '#000000'})
const styles2 = theme => ({root: {backgroundColor: '#fff'})
on my react component I have
export default compose(
withStyles(styles, {withTheme: true}),
I need to determine what style to use in render() what is the best way to do that ?
After long investigation the best solution I came with is as follows:
I have imported classNames package
Used only one style
const styles = theme => ({
whiteRoot: {
backgroundColor: '#fff',
},
blackRoot: {
backgroundColor: '#000000',
},
})
and on render()
for example
<Grid container className={classNames(classes[`${black}Root`])} justify='center'>
and worked fine

Divider color change React Material Ui

I'm working with the divider component of the material ui framework and am stuck with the color changing aspect. With most other components from this framework I've been able to change the color by applying the useStyles() method as such:
const useStyles = makeStyles(theme => ({
textPadding: {
paddingTop: 10,
paddingBottom: 10,
color:'white',
},
}));
But I'm not able to change the color of the dividers using the same approach:
const useStyles = makeStyles(theme => ({
dividerColor: {
backgroundColor: 'white',
},
}));
I of-course then apply it to the component:
<Divider classname={classes.dividerColor}></Divider>
I looked up the docs for it but can't figure out what I've done wrong. Could someone give me a helping hand?
use the classes API to change the divider color:
const useStyles = makeStyles((theme) => ({
divider: {
// Theme Color, or use css color in quote
background: theme.palette.divider,
},
}));
<Divider classes={{root: classes.divider}} />
Divider API, To get your head around Material UI Theme
To change Divider line color in MUI v5 you need to adjust your approach depending on whether the element has children or not.
For an empty Divider:
<Divider sx={{ bgcolor: "secondary.light" }} />
For a Divider with content:
<Divider
sx={{
"&::before, &::after": {
borderColor: "secondary.light",
},
}}
>
<Typography>Some Text</Typography>
</Divider>
Comparing to the other answers for v5, note that you do not need to nest the SX props under &.MuiDivider-root and you can use the theme properties with the SX shorthand strings (e.g., secondary.light instead of (theme) => theme.palette.secondary.light.
You can use
<Divider style={{ background: 'black' }} variant="middle" />
You have to override the CSS using classes.
<Divider classes={{root: classes.dividerColor}} />
See the Material UI docs on CSS overrides: https://material-ui.com/customization/components/#overriding-styles-with-classes
You can directly add color attribute to the divider like so
<Divider color="#FDA228" sx={{ height: 2, width: '92px' }} />
the result would be something like this
You should always use className while using material-ui styling instead of typical javascript style declaration like classname.
You can refer to the official doc also: https://material-ui.com/styles/basics/#hook-api
Using #mui v5 I recognized this was the only way to make it work for myself.
Note:
Because my Divider item has text, the ::before and ::after css
selectors specify which side of the divider to style.
<Divider
sx={{
'&.MuiDivider-root': {
'&::before': {
borderTop: `thin solid ${theme?.palette.primary['700']}`
}
}
}}
style={{
color: "white",
}}
variant="middle"
> Editing as - {username} </Divider>
Example with className :
const useStyles = makeStyles((theme) => ({
divider: {
background: "white",
},
}));
<Divider className={classes.divider} />
In the latest MUI(v5), This is how it is done:
<Divider
sx={{ bgcolor: (theme) => theme.palette.divider }}
style={{
border: "none",
height: 2,
margin: 0,
}}
/>
You can do it with createTheme function inside the react component
const Theme = createTheme({
components: {
MuiDivider: {
variants: [
{
props: { variant: 'dynamic' },
style: {
":before": {
borderTop: "thin solid #ffffff"
},
":after": {
borderTop: "thin solid #ffffff"
},
}
}
]
}
},
})
Use it with the variant key in the html component
<Divider variant={'dynamic'} flexItem></Divider>

How to override (overwrite) classes and styles in material-ui (React)

I'm using version 1.2.1 of material-ui and I'm trying to override the AppBar component to be transparent. The documentation outlines how to override styles here.
My code:
import React, { Component } from 'react';
import AppBar from '#material-ui/core/AppBar';
import Toolbar from '#material-ui/core/Toolbar';
import logo from '../Assets/logo.svg';
class NavigationBar extends Component {
render() {
const styles = {
root: {
backgroundColor: 'transparent',
boxShadow: 'none',
},
};
return (
<AppBar position={this.props.position} classes={{ root: styles.root }}>
<Toolbar>
<img src={logo} style={{ height: '28px' }} />
</Toolbar>
</AppBar>
);
}
}
export default NavigationBar;
But this yields no results. Am I trying to override wrong? Not sure where I'm going wrong here...
This answer makes #Nadun answer complete - he deserves the credit.
To override material ui classes we need to understand these things:
1. Add your styles in a const variable at the top
const styles = {
root: {
backgroundColor: 'transparent !important',
boxShadow: 'none',
paddingTop: '25px',
color: '#FFFFFF'
}
};
2. We need to use higher order function with "withStyles" to override material ui classes
export default withStyles(styles)(NavigationBar);
3. Now these styles are available to us as props in the render function
try doing this - console.log(this.props.classes) - you get a classes name correspoding to properties you include in styles object,
like - {root: "Instructions-root-101"}.
Add that with classes attribute
render() {
const { classes } = this.props;
return (
<AppBar classes={{ root: classes.root }}>
// Add other code here
</AppBar>
)
}
import React, { Component } from 'react';
import AppBar from '#material-ui/core/AppBar';
import Toolbar from '#material-ui/core/Toolbar';
import logo from '../Assets/logo.svg';
import { withStyles } from '#material-ui/core/styles';
const styles = {
transparentBar: {
backgroundColor: 'transparent !important',
boxShadow: 'none',
paddingTop: '25px',
color: '#FFFFFF'
}
};
class NavigationBar extends Component {
render() {
return (
<AppBar className={classes.transparentBar}>
<Toolbar>
<img src={logo} style={{ height: '28px' }} />
</Toolbar>
</AppBar>
);
}
}
export default withStyles(styles)(NavigationBar);
find the important part as :
backgroundColor: 'transparent !important'
refer this guide for more details: https://material-ui.com/customization/overrides/
hope this will help you
Adding to above answers, if you want to add style to some internal autogenerated element, you can do this using this syntax
<TextField className={classes.txtField}
then in the classes object, we can approach the label present inside TextField via this way
const useStyles = makeStyles((theme) => ({
txtField: {
"& label": {
padding: 23
}
}
});
import ...;
import { withStyles } from '#mui/styles';
const styles = {
transparentBar: {
backgroundColor: 'transparent !important',
boxShadow: 'none',
paddingTop: '25px',
color: '#FFFFFF'
}
};
function NavigationBar (props) {
const { classes } = props;
return (
<AppBar className={classes.transparentBar}>
<Toolbar>
<img src={logo} style={{ height: '28px' }} />
</Toolbar>
</AppBar>
);
}
export default withStyles(styles)(NavigationBar);
It works for me.
note! update MUI core version

Categories

Resources