I am migrating a codebase from Material-Ui v4 to Material-Ui v5. After doing this, the Select component started to open horizontally instead of vertically as the image below:
This is the code:
import Select from "#mui/material/Select";
import makeStyles from "#mui/styles/makeStyles";
import {
FormControl
} from "#mui/material";
import { styled as styledMui } from "#mui/material/styles";
const PlanSelect = styledMui(Select)({
fieldset: {
legend: {
width: "unset",
},
},
});
export const useStyles = makeStyles((theme) => ({
planSelect: {
float: "right",
width: "350px",
backgroundColor: "white",
marginBottom: 15,
},
}));
...
const CustomComponent = ()=>{
...
return(
...
<FormControl variant="outlined" className={classes.planSelect}>
<PlanSelect
value={productId}
onChange={({ target: { value } }) => setProductId(value)}>
<MenuItem value="standard">Option A</MenuItem>
<MenuItem value="pro">Option B</MenuItem>
</PlanSelect>
</FormControl>
)
Classes:
How can I make the options list from the Select to open vertically as Material-Ui v4 ?
Currently trying to figure out how to render the styles(without having to do inline styles) from the styles object for the stepper component. However, it is giving me an error when I try to do something similar to what Material UI's demo gave me. I took bits and pieces from it basically and tried to implement it in my code. Here is what Material UI's demo looks like which I want to replicate as well.
And here is the code they have
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%)',
}),
}));
function ColorlibStepIcon(props) {
const { active, completed, className } = props;
const icons = {
1: <SettingsIcon />,
2: <GroupAddIcon />,
3: <VideoLabelIcon />,
};
return (
<ColorlibStepIconRoot ownerState={{ completed, active }} className={className}>
{icons[String(props.icon)]}
</ColorlibStepIconRoot>
);
}
I figured I could scrap the HOC component(color step icon root) and just do without root. Also, they are importing styled from
import { styled } from '#mui/material/styles';
Which when I try to do, its undefined. So I tried to use it in the styles object the way Ive been always doing with withStyles.
But am getting this error:
Here is my code:
import React from 'react';
import { Typography } from '#material-ui/core';
import { withStyles } from '#material-ui/core/styles';
import Stepper from '#material-ui/core/Stepper';
import Step from '#material-ui/core/Step';
import StepLabel from '#material-ui/core/StepLabel';
import Icon from '#material-ui/core/Icon';
import PropTypes from 'prop-types';
const styles = theme => ({
stepLabelRoot: {
fontWeight: 'bold',
color: '#fff',
display: 'flex',
flexDirection: 'column',
alignItems: 'center'
},
checklistHeader: {
fontWeight: 'bold',
marginTop: '80px',
color: 'white'
},
connectorIcon: {
color: theme.palette.text.secondary
},
active: {
backgroundColor: 'green'
},
stepper: {
background: 'none',
fontWeight: 'bold',
height: '500px'
},
checklistImage: {
width: '42px',
height: '42px'
}
});
const steps = ['Are you there?', 'Adopt', 'Buy'];
const Checklist = ({ classes }) => {
const ColorlibStepIcon = ({
icon, completed, className, classes, theme
}) => {
const icons = {
1: <img className={classes.checkListImage} src="https://i.pinimg.com/474x/be/54/bd/be54bd5e8e9c23e3ce570ff2acae592d.jpg" alt="check" />,
2: <img className={classes.checkListImage} src="https://i.pinimg.com/474x/be/54/bd/be54bd5e8e9c23e3ce570ff2acae592d.jpg" alt="check" />,
3: <img className={classes.checkListImage} src="https://i.pinimg.com/474x/be/54/bd/be54bd5e8e9c23e3ce570ff2acae592d.jpg" />,
};
return (
<div ownerState={{ completed }} className={className}>
{icons[String(icon)]}
</div>
);
};
return (
<React.Fragment>
<Typography variant="h6" align="center" gutterBottom className={classes.checklistHeader}>Check the following</Typography>
<Stepper alternativeLabel activeStep={2} className={classes.stepper}>
{steps.map(label => (
<Step key={label}>
<StepLabel classes={{ root: classes.stepLabelRoot }} StepIconComponent={ColorlibStepIcon}>
<div className={classes.stepLabelRoot}>
{label}
</div>
<span>
Lorem Ipsum
</span>
</StepLabel>
</Step>
))}
</Stepper>
</React.Fragment>
);
};
Checklist.defaultProps = {
};
Checklist.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles(styles, { withTheme: true })(Checklist);
You have 2 bugs in your code. In your icon component:
<img className={classes.checkListImage}
The rule name you defined above is called checklistImage not checkListImage, so change it to:
<img className={classes.checklistImage}
Secondly, the classes from the Checklist component is shadowed by the classes inside ColorlibStepIcon:
const ColorlibStepIcon = ({
icon,
completed,
className,
theme,
/*classes <-- this classes is undefined which shadows the real classes
passing from above, so remove it */
}) => {
How can you override the Material-UI theme using styles without using !important?
const theme = createMuiTheme({
overrides: {
MuiInputBase: {
input: {
background: '#dd7711',
padding: 10,
},
},
},
},
})
export default makeStyles(theme => ({
hutber: {
background: '#000',
color: '#fff',
},
}))
function SpacingGrid() {
const classes = useStyles()
return <MuiThemeProvider theme={theme}><Input label="Outlined" variant="outlined" className={classes.hutber} /></MuiThemeProvider>
}
Output:
As you can see, the only way to override the styles are be creating another theme :O I would like to know if styles
The reason the override was not working was because specifying the className prop is equivalent to specifying the root CSS class for Input, but your theme overrides are on the input CSS class which is applied to a different element (the root element is a div, the input element is an <input> element within that div).
In my example below, you can see two different approaches for targeting the <input> element. The first approach uses a nested selector to target .MuiInputBase-input. The second approach uses the classes prop (instead of className) and provides the overrides as the input CSS class.
import React from "react";
import ReactDOM from "react-dom";
import {
createMuiTheme,
MuiThemeProvider,
makeStyles
} from "#material-ui/core/styles";
import Input from "#material-ui/core/Input";
const theme = createMuiTheme({
overrides: {
MuiInputBase: {
input: {
background: "#dd7711",
padding: 10
}
}
}
});
const useStyles = makeStyles(theme => ({
hutber: {
"& .MuiInputBase-input": {
background: "#000",
color: "#fff"
}
},
alternateApproach: {
background: "#000",
color: "#fff"
}
}));
function App() {
const classes = useStyles();
return (
<MuiThemeProvider theme={theme}>
<Input defaultValue="Without overrides" variant="outlined" />
<br />
<br />
<Input
defaultValue="With overrides"
variant="outlined"
className={classes.hutber}
/>
<br />
<br />
<Input
defaultValue="Alternate approach"
variant="outlined"
classes={{ input: classes.alternateApproach }}
/>
</MuiThemeProvider>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
The input text in a Material-UI Multiline TextField is overlapping each other (not the label).
See sample and code in CodeSandBox: https://codesandbox.io/s/keen-wu-yquk6
I suspect it may have something to do with the fact that I increased the Font-Sized to 30, but the line-height (or something else) remained configured for the default size font.
Samples screenshots:
import React from "react";
import styled from "styled-components";
import { makeStyles } from "#material-ui/core/styles";
import TextField from "#material-ui/core/TextField";
const useStyles = makeStyles(theme => ({
container: {
display: "flex",
flexWrap: "wrap"
},
textField: {
marginLeft: theme.spacing(1),
marginRight: theme.spacing(1),
width: 350
}
}));
const StyledTextField = styled(TextField)`
.MuiInput-underline::before {
border-bottom-color: white;
}
.MuiInput-underline:hover:not(.Mui-disabled)::before {
border-bottom-color: white;
}
.MuiInput-underline::after {
border-bottom-color: #fdcd39;
}
`;
const StyledTextArea1 = ({ Label, fieldType, handleChange }) => {
const classes = useStyles();
return (
<StyledTextField
id="standard-basic"
className={classes.textField}
label="Test Label"
multiline
fullWidth
rows="5"
variant="outlined"
margin="normal"
// onChange={handleChange(fieldType)}
InputLabelProps={{
style: {
color: "black",
fontSize: 30,
borderBottom: "white",
fontFamily: "Akrobat"
}
}}
inputProps={{
style: {
fontSize: 30,
color: "#fdcd39",
fontFamily: "Akrobat",
fontWeight: 800
}
}}
/>
);
};
export { StyledTextArea1 };
Any assistance greatly appreciated.
Setting the font styles via inputProps defines those styles on the textarea element whereas Material-UI controls the font size on a div (with the MuiInputBase-root CSS class) that wraps the textarea. If you move where you control the font styles to target .MuiInputBase-root, it works as desired.
import React from "react";
import styled from "styled-components";
import { makeStyles } from "#material-ui/core/styles";
import TextField from "#material-ui/core/TextField";
const useStyles = makeStyles(theme => ({
container: {
display: "flex",
flexWrap: "wrap"
},
textField: {
marginLeft: theme.spacing(1),
marginRight: theme.spacing(1),
width: 350
}
}));
const StyledTextField = styled(TextField)`
.MuiInputBase-root {
font-size: 30px;
color: #fdcd39;
font-family: Akrobat;
font-weight: 800;
}
.MuiInput-underline::before {
border-bottom-color: white;
}
.MuiInput-underline:hover:not(.Mui-disabled)::before {
border-bottom-color: white;
}
.MuiInput-underline::after {
border-bottom-color: #fdcd39;
}
`;
const StyledTextArea1 = ({ Label, fieldType, handleChange }) => {
const classes = useStyles();
return (
<StyledTextField
id="standard-basic"
className={classes.textField}
label="Test Label"
defaultValue="Default Value"
multiline
fullWidth
rows="5"
variant="outlined"
margin="normal"
// onChange={handleChange(fieldType)}
InputLabelProps={{
style: {
color: "black",
fontSize: 30,
borderBottom: "white",
fontFamily: "Akrobat"
}
}}
/>
);
};
export { StyledTextArea1 };
In my sandbox, I also added <StylesProvider injectFirst> around everything in index.js to ensure that the styled-components CSS classes are injected after the Material-UI CSS classes in the <head> so that your style overrides via styled-components will win in cases where specificity is the same.
I am struggling to modify button colors in MUI next (v1).
How would I set muitheme to behave similarity to bootstrap, so I could just use "btn-danger" for red, "btn-success" for green... ?
I tried with custom className but it doesn't work properly (hover color does't change) and it seems repetitive. What options do I have?
In MUI v5, this is how you create customized colors in your theme for your MUI Button. The primary and secondary colors are created the same way under the hood:
const { palette } = createTheme();
const { augmentColor } = palette;
const createColor = (mainColor) => augmentColor({ color: { main: mainColor } });
const theme = createTheme({
palette: {
anger: createColor('#F40B27'),
apple: createColor('#5DBA40'),
steelBlue: createColor('#5C76B7'),
violet: createColor('#BC00A3'),
},
});
Usage
<Button color="anger" variant="contained">
anger
</Button>
<Button color="apple" variant="contained">
apple
</Button>
<Button color="steelBlue" variant="contained">
steelBlue
</Button>
<Button color="violet" variant="contained">
violet
</Button>
If you're using typescript, you also need to add additional types for the colors you just defined:
declare module '#mui/material/styles' {
interface CustomPalette {
anger: PaletteColorOptions;
apple: PaletteColorOptions;
steelBlue: PaletteColorOptions;
violet: PaletteColorOptions;
}
interface Palette extends CustomPalette {}
interface PaletteOptions extends CustomPalette {}
}
declare module '#mui/material/Button' {
interface ButtonPropsColorOverrides {
anger: true;
apple: true;
steelBlue: true;
violet: true;
}
}
Live Demo
Related Answers
How to add custom MUI palette colors
Change primary and secondary colors in MUI
You can try this
<Button
style={{
borderRadius: 35,
backgroundColor: "#21b6ae",
padding: "18px 36px",
fontSize: "18px"
}}
variant="contained"
>
Submit
</Button>
I came up with this solution using Brendans answer in this thread. Hopefully it'll help someone in a similar situation.
import React, { Component } from 'react'
import { MuiThemeProvider, createMuiTheme } from 'material-ui/styles'
import Button from 'material-ui/Button'
import { red, blue } from 'material-ui/colors'
const redTheme = createMuiTheme({ palette: { primary: red } })
const blueTheme = createMuiTheme({ palette: { primary: blue } })
class Buttons extends Component {
render = () => (
<div className="ledger-actions-module">
<MuiThemeProvider theme={redTheme}>
<Button color="primary" variant="raised">
Delete
</Button>
</MuiThemeProvider>
<MuiThemeProvider theme={blueTheme}>
<Button color="primary" variant="raised">
Update
</Button>
</MuiThemeProvider>
</div>
)
}
There is a mistake with Bagelfp's answer, and some other things to consider;
First, 'error' is not a supported color theme in material-ui#next v1's Button component. Only 'default', 'inherit', 'primary' and 'secondary' are accepted by the color prop.
Here is the approach I have found to be the easiest so far. First, choose your two most common theme colors and place them at the root of your app.
import React from 'react';
import { Component } from './Component.js'
import { MuiThemeProvider, createMuiTheme } from 'material-ui/styles';
const theme = createMuiTheme({
palette: {
primary: 'purple',
secondary: 'green',
error: 'red',
},
});
export class App extends Component {
render() {
return (
<MuiThemeProvider theme={theme}>
<Component />
...
</MuiThemeProvider>
);
}
}
Then in your component, choose the theme with your desired color;
import React from 'react';
import Button from 'material-ui/Button';
export const Component = (props) => (
<div>
<Button variant="fab" color="primary">
I am purple, click me!
</Button>
</div>
)
If you need a third and fourth color, you can export Component.js with a new palette just like you did in App.js.
This is the only solution I have found that allows me to retain the darkened hover effect (none of the official override examples retain functioning hover). I really wish I could find a way to simply drop in a new theme color when calling Button, but for now this is the most simple way to do it.
EDIT: My new preferred method is to create a CustomButton component using styled-components and material-ui buttonbase. I also place the styled-components theme provider at the root of my app alongside my MuiThemeProvider. This gives me easy access to additional theme colors in all my styled-components without importing and dropping in more ThemeProviders. In the case of my CustomButton, I just give it a theme prop, which is passed right down to the css in styled(ButtonBase). See the styled-component docs for more info.
Try this:
import * as React from 'react';
import Button, { ButtonProps } from "#material-ui/core/Button";
import { Theme } from '#material-ui/core';
import { withStyles } from '#material-ui/styles';
const styles: (theme: Theme) => any = (theme) => {
return {
root:{
backgroundColor: theme.palette.error.main,
color: theme.palette.error.contrastText,
"&:hover":{
backgroundColor: theme.palette.error.dark
},
"&:disabled":{
backgroundColor: theme.palette.error.light
}
}
};
};
export const ButtonContainedError = withStyles(styles)((props: ButtonProps) => {
const { className, ...rest } = props;
const classes = props.classes||{};
return <Button {...props} className={`${className} ${classes.root}`} variant="contained" />
});
Now you have a ButtonContainedError to use anywhere.
And it is consistent with your theme.
Here is an example typescript implementation:
import React from "react";
import { createStyles, Theme, makeStyles } from "#material-ui/core/styles";
import capitalize from "lodash/capitalize";
import MuiButton, {
ButtonProps as MuiButtonProps
} from "#material-ui/core/Button";
export type ColorTypes =
| "primary"
| "secondary"
| "error"
| "success"
| "warning"
| "default"
| "inherit"
| "info";
type ButtonProps = { color: ColorTypes } & Omit<MuiButtonProps, "color">;
const useStyles = makeStyles<Theme>(theme =>
createStyles({
outlinedSuccess: {
borderColor: theme.palette.success.main,
color: theme.palette.success.main
},
outlinedError: {
borderColor: theme.palette.error.main,
color: theme.palette.error.main
},
outlinedWarning: {
borderColor: theme.palette.warning.main,
color: theme.palette.warning.main
},
outlinedInfo: {
borderColor: theme.palette.info.main,
color: theme.palette.info.main
},
containedSuccess: {
backgroundColor: theme.palette.success.main,
color: theme.palette.success.contrastText,
"&:hover": {
backgroundColor: theme.palette.success.dark
}
},
containedError: {
backgroundColor: theme.palette.error.main,
color: theme.palette.error.contrastText,
"&:hover": {
backgroundColor: theme.palette.error.dark
}
},
containedWarning: {
backgroundColor: theme.palette.warning.main,
color: theme.palette.warning.contrastText,
"&:hover": {
backgroundColor: theme.palette.warning.dark
}
},
containedInfo: {
backgroundColor: theme.palette.info.main,
color: theme.palette.info.contrastText,
"&:hover": {
backgroundColor: theme.palette.info.dark
}
}
})
);
const Button: React.FC<ButtonProps> = ({ children, color, ...props }) => {
const classes = useStyles();
const className = classes?.[`${props.variant}${capitalize(color)}`];
const colorProp =
["default", "inherit", "primary", "secondary"].indexOf(color) > -1
? (color as "default" | "inherit" | "primary" | "secondary")
: undefined;
return (
<MuiButton {...props} color={colorProp} className={className}>
{children}
</MuiButton>
);
};
Button.displayName = "Button";
export default Button;
with this you can do <Button variant="contained" color="success"> with autocomplete and warning free :)
Update:
In Material UI V5 this is achievable in a much more elegant way. You can just add a color to the palette and the button will automatically support it! Their documentation has a great example of how to do this: https://mui.com/customization/palette/#adding-new-colors
You can use theme.palette.getContrastText() to calculate the correct text color based on a background color value.
import { Button, makeStyles } from '#material-ui/core';
const useStyles = makeStyles((theme) => ({
deleteButton: {
// to make a red delete button
color: theme.palette.getContrastText(theme.palette.error.main),
background: theme.palette.error.main,
}
}));
export const DeleteButton = () => {
const classes = useStyles();
return (
<Button className={classes.deleteButton}>Delete</Button>
);
}
first try to install npm install #material-ui/styles the
apply styles according to material documentation, for react class component you can use below code:
import React, {Component} from "react";
import { styled } from '#material-ui/styles';
import Button from '#material-ui/core/Button';
const MyButton = styled(Button)({
background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
border: 0,
borderRadius: 3,
boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
color: 'white',
height: 48,
padding: '0 30px',
});
class AprinClass extends Component {
render() {
return (
<MyButton>Styled Components</MyButton>
)
}
}
export default AprinClass;
for more information with references please check my blog in medium.
https://medium.com/#farbodaprin/how-to-make-a-customisable-material-ui-button-a85b6534afe5
You could create a theme with palettes defined for each of their 3 supported intentions (primary, secondary, error), and then use the color prop on <Button> to use those. In your example the btn-danger could be <Button color='error'>
EDIT: Brendan's answer is correct here that error is not supported for Button. According to the documentation Button only supports intentions that "make sense for this component.", so only primary and secondary would work here.
From their docs (trimmed down a little here):
const theme = createMuiTheme({
palette: {
primary: purple,
secondary: red
}
});
function Palette() {
return (
<MuiThemeProvider theme={theme}>
<div>
<Button color="primary">{'Primary'}</Button>
<Button color="secondary">{'Secondary'}</Button>
</div>
</MuiThemeProvider>
);
}
See Brendan's Answer for a more realistic example of creating themes for your components.
The easiest way to change the button color is to add the "style" attribute. Here's an example of a green button I created:
import Button from '#material-ui/core/Button';
<Button
variant="contained"
color="primary"
style={{ backgroundColor: '#357a38' }}
>
Run
</Button>
From 2022/05:
According to the official Doc: Customize MUI with your theme, you need to use ThemeProvider and createTheme.
First, customize the primary color like this,
import {ThemeProvider, createTheme} from '#mui/material/styles';
const theme = createTheme({
palette: {
primary: {
main: '#000000',
},
},
});
Then wrap your App or anywhere your want with the ThemeProvider component, and set the color props of your Button component to primary.
function YourApp() {
// logic omitted
return (
<ThemeProvider theme={theme}>
<YourApp>
<Button color="primary">Click me</Button>
</YourApp>
</ThemeProvider>
);
}
I found out that !important works in the classes. (React Hooks)
const styles "...etc..." = (theme: Theme) => ({
buttonWarning: {
backgroundColor: theme.palette.warning.dark + '!important'
}
}))
Then in the button
const classes = styles();
<Button className={classes.buttonWarning}>Hello</Button>
Use This sx props it gives more understanding and also more relative to the MUI. in most of the MUI components, they use these props.
import {Button} from '#mui/material'
<Button variant="contained" sx={{
borderRadius: 35,
backgroundColor: "#21b6ae",
padding: "18px 36px",
fontSize: "18px",
**color:"white"**
}} >
elevation
</Button>
Export any color from '#mui/material/colors'; (Docs)
import { pink } from '#mui/material/colors';
and use like this
<Button variant="contained" sx={{ backgroundColor: pink[700] }}>Check</Button>