I am a React newbie. Using Material-UI / React, how can I create my own Button component? Ideally, I would like the component to encapsulate certain properties.
Here is my code.
export const Button = withSytles((theme) => ({
root: {
backgroundColor: theme.palette.primary.main,
minWidth: '100px',
}
}))(MaterialButton);
This code is working however, is there a way to have the component employ all of the properties when I use color="primary" to the Material-UI Button. Do I need to include ALL of the properties or is there an easier way.
Also, I am sure using 100px is not the correct way for this control to be responsive. Is 100em correct or should I use something different?
This is possible in Material-UI v5, you can create a custom variant for your Button. A variant is just a specific styles of a component, each variant is identified by a set of component props. See the example below:
const defaultTheme = createMuiTheme();
const theme = createMuiTheme({
components: {
MuiButton: {
variants: [
{
props: { color: "primary", variant: "contained" },
style: {
backgroundColor: defaultTheme.palette.primary.main,
fontSize: 20,
minWidth: "200px"
}
},
{
props: { color: "secondary", variant: "contained" },
style: {
backgroundColor: defaultTheme.palette.secondary.main
}
}
]
}
}
});
When you render this component:
<Button color="primary" variant="contained">
Primary
</Button>
The first variant style specified above is used because they have the same props:
{ color: "primary", variant: "contained" }
Live Demo
You can create custom variant as mentioned by #NearHuscarl other way you can create component modifying style.
Something like.
import { makeStyles } from '#material-ui/core/styles'
import Button from '#material-ui/core/Button'
import PropTypes from 'prop-types'
const useStyles = makeStyles((theme) => ({
root: {
height: '48px',
width: '100%',
backgroundColor: '#232323',
color: '#fff',
fontSize: '16px',
borderRadius: '4',
minHeight: theme.spacing(6),
'&:hover, &:active, &:focus': {
backgroundColor: `rgba(0, 0, 0, 0.8)`,
},
'&.Mui-disabled': {
opacity: 0.75,
},
},
}))
const propTypes = {
loading: PropTypes.bool,
}
function PrimaryButton({ children, loading = false, ...props }) {
const classes = useStyles()
return (
<Button
variant="contained"
className={classes.root}
disabled={loading}
{...props}
>
{children}
</Button>
)
}
PrimaryButton.propTypes = propTypes
export default PrimaryButton
Created code sandbox
https://codesandbox.io/embed/boring-mayer-cjl0f?fontsize=14&hidenavigation=1&theme=dark
I am trying to override the Material UI linear progress bar colours. The first solution I tried (simplified) is below.
import React from "react";
import { makeStyles } from "#material-ui/core/styles";
import LinearProgress from "#material-ui/core/LinearProgress";
const useStyles = makeStyles({
colorPrimary: {
backgroundColor: "#f6ce95"
},
barColorPrimary: {
backgroundColor: "#f0ad4e"
},
dashedColorPrimary: {
backgroundImage:
"radial-gradient(#f6ce95 0%, #f6ce95 16%, transparent 42%)"
}
});
export default function LinearDeterminate() {
const classes = useStyles();
return (
<LinearProgress
variant="determinate"
color="primary"
valueBuffer={40}
value={20}
classes={{
colorPrimary: classes.colorPrimary,
dashedColorPrimary: classes.dashedColorPrimary,
barColorPrimary: classes.barColorPrimary
}}
/>
);
}
The above works fine with all but the buffer variant.
The second solution I tried is the following.
import React from "react";
import { makeStyles } from "#material-ui/core/styles";
import LinearProgress from "#material-ui/core/LinearProgress";
const useStyles = makeStyles({
root: {
"& .MuiLinearProgress-colorPrimary": {
backgroundColor: "#f6ce95"
},
"& .MuiLinearProgress-barColorPrimary": {
backgroundColor: "#f0ad4e"
},
"& .MuiLinearProgress-dashedColorPrimary": {
backgroundImage:
"radial-gradient(#f6ce95 0%, #f6ce95 16%, transparent 42%)"
}
},
});
export default function LinearDeterminate() {
const classes = useStyles();
return (
<LinearProgress
variant="buffer"
color="primary"
valueBuffer={40}
value={20}
classes={{
root: classes.root,
}}
/>
);
}
The above works fine with the buffer variant, but not any of the others.
How would I make all variants work with a custom colour?
I have been using this small code sandbox here: https://codesandbox.io/s/material-demo-forked-w0t06?file=/demo.js
On your second solution, negate the first rule for the buffer: :not(.MuiLinearProgress-buffer). Also, the buffer .MuiLinearProgress-colorPrimary seems to be a root descendant - see my second rule
const useStyles = makeStyles({
root: {
height: "40px",
"&.MuiLinearProgress-colorPrimary:not(.MuiLinearProgress-buffer)": {
backgroundColor: "#f6ce95"
},
"& .MuiLinearProgress-colorPrimary": {
backgroundColor: "#f6ce95"
},
"& .MuiLinearProgress-barColorPrimary": {
backgroundColor: "#f0ad4e"
},
"& .MuiLinearProgress-dashedColorPrimary": {
backgroundImage:
"radial-gradient(#f6ce95 0%, #f6ce95 16%, transparent 42%)"
}
}
});
<LinearProgress
variant="determinate"
color="primary"
valueBuffer={40}
value={20}
classes={{
root: classes.root
}}
/>
How can I override a rule of a class which has high specificity?
For example, the .MuiAccordionSummary-content.Mui-expanded class in the AccordionSummary
const useStyles = makeStyles(() => ({
expanded: {
marginBottom: 0,
},
}));
in combination with:
<AccordionSummary classes={{
expanded: classes.expanded,
}}/>
is applied but overridden.
Note: marginBottom: '0 !important' works, but doesn't feel like an optimal solution.
You could use global overrides to change the default margin of the AccordionSummary. However, this will affect all AccordionSummary components in your application.
The better approach (the one you are already using) is to wrap the component and alter its classes. If you look into the source of the AccordionSummary, you will find that the expanded property is an empty block. The margin gets set by the referencing selector in the content property:
content: {
display: 'flex',
flexGrow: 1,
transition: theme.transitions.create(['margin'], transition),
margin: '12px 0',
'&$expanded': {
margin: '20px 0',
},
},
If you add the same reference in your custom styles, the priority becomes higher and you won't need !important. You will have to add the expanded className to your custom styles though:
import React from 'react';
import makeStyles from '#material-ui/core/styles/makeStyles'
import Accordion from '#material-ui/core/Accordion';
import AccordionDetails from '#material-ui/core/AccordionDetails';
import AccordionSummary from '#material-ui/core/AccordionSummary';
const useStyles = makeStyles(() => ({
expanded: {},
content: {
'&$expanded': {
marginBottom: 0,
},
},
}));
const MyAccordion = ({ summary, details }) => {
const classes = useStyles();
return (
<Accordion>
<AccordionSummary classes={{ content: classes.content, expanded: classes.expanded }}>
{summary}
</AccordionSummary>
<AccordionDetails>
{details}
</AccordionDetails>
</Accordion>
)
};
export default MyAccordion;
I have this component
import React, { FC } from "react";
import { Avatar } from "#material-ui/core";
export interface AvatarProps {
alt?: string;
src: string;
variant?: "circle" | "rounded" | "square";
sizes?: string;
}
const Component: FC<AvatarProps> = (props: AvatarProps): JSX.Element => {
return <Avatar {...props}></Avatar>;
};
export default Component;
I am trying to set the sizes property but it is not changing. What exactly does it take value?
MUI 5
Using the sx prop provided by the library:
<Avatar sx={{ height: '70px', width: '70px' }}></Avatar>
...or my preferred method, create a styled component outside your functional component or class. Something like this:
const StyledAvatar = ({ children, ...props }) => (
<Avatar sx={{ height: '70px', width: '70px' }} {...props}>
{children}
</Avatar>
);
Usage:
<StyledAvatar alt="add other props as normal">
Children can be nested here
</StyledAvatar>;
Material UI 4 (Original Answer)
Scroll down to the sizes attribute of img and have a read.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img
Or just use makeStyles as seen in the documentation:
https://v4.mui.com/components/avatars/#SizeAvatars.js
Or another option is a simple inline style:
<Avatar style={{ height: '70px', width: '70px' }}></Avatar>
You can set the size with a classname and the theme.spacing from Material UI.
const useStyles = makeStyles((theme) => ({
sizeAvatar: {
height: theme.spacing(4),
width: theme.spacing(4),
},
}));
...
const classes = useStyles();
<Avatar src="/path/to/image" alt="Avatar" className={classes.sizeAvatar} />
You can try setting additional Avatar Props
<AvatarGroup
componentsProps={{
additionalAvatar: {
sx: {
height: 30,
width: 30,
background: "red"
}
}
}
}
max={2}>
....
Formatted by https://st.elmah.io
How can I style MUI Tooltip text? The default tooltip on hover comes out black with no text-wrap. Is it possible to change the background, color etc? Is this option even available?
The other popular answer (by André Junges) on this question is for the 0.x versions of Material-UI. Below I've copied in my answer from Material UI's Tooltip - Customization Style which addresses this for v3 and v4. Further down, I have added a version of the example using v5.
Below are examples of how to override all tooltips via the theme, or to just customize a single tooltip using withStyles (two different examples). The second approach could also be used to create a custom tooltip component that you could reuse without forcing it to be used globally.
import React from "react";
import ReactDOM from "react-dom";
import {
createMuiTheme,
MuiThemeProvider,
withStyles
} from "#material-ui/core/styles";
import Tooltip from "#material-ui/core/Tooltip";
const defaultTheme = createMuiTheme();
const theme = createMuiTheme({
overrides: {
MuiTooltip: {
tooltip: {
fontSize: "2em",
color: "yellow",
backgroundColor: "red"
}
}
}
});
const BlueOnGreenTooltip = withStyles({
tooltip: {
color: "lightblue",
backgroundColor: "green"
}
})(Tooltip);
const TextOnlyTooltip = withStyles({
tooltip: {
color: "black",
backgroundColor: "transparent"
}
})(Tooltip);
function App(props) {
return (
<MuiThemeProvider theme={defaultTheme}>
<div className="App">
<MuiThemeProvider theme={theme}>
<Tooltip title="This tooltip is customized via overrides in the theme">
<div style={{ marginBottom: "20px" }}>
Hover to see tooltip customized via theme
</div>
</Tooltip>
</MuiThemeProvider>
<BlueOnGreenTooltip title="This tooltip is customized via withStyles">
<div style={{ marginBottom: "20px" }}>
Hover to see blue-on-green tooltip customized via withStyles
</div>
</BlueOnGreenTooltip>
<TextOnlyTooltip title="This tooltip is customized via withStyles">
<div>Hover to see text-only tooltip customized via withStyles</div>
</TextOnlyTooltip>
</div>
</MuiThemeProvider>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Here is documentation on tooltip CSS classes available to control different aspects of tooltip behavior: https://material-ui.com/api/tooltip/#css
Here is documentation on overriding these classes in the theme: https://material-ui.com/customization/components/#global-theme-override
Here is a similar example, but updated to work with v5 of Material-UI (pay attention that it works in 5.0.3 and upper versions after some fixes). It includes customization via the theme, customization using styled, and customization using the sx prop. All of these customizations target the "tooltip slot" so that the CSS is applied to the element that controls the visual look of the tooltip.
import React from "react";
import ReactDOM from "react-dom";
import { createTheme, ThemeProvider, styled } from "#mui/material/styles";
import Tooltip from "#mui/material/Tooltip";
const defaultTheme = createTheme();
const theme = createTheme({
components: {
MuiTooltip: {
styleOverrides: {
tooltip: {
fontSize: "2em",
color: "yellow",
backgroundColor: "red"
}
}
}
}
});
const BlueOnGreenTooltip = styled(({ className, ...props }) => (
<Tooltip {...props} componentsProps={{ tooltip: { className: className } }} />
))(`
color: lightblue;
background-color: green;
font-size: 1.5em;
`);
const TextOnlyTooltip = styled(({ className, ...props }) => (
<Tooltip {...props} componentsProps={{ tooltip: { className: className } }} />
))(`
color: black;
background-color: transparent;
`);
function App(props) {
return (
<ThemeProvider theme={defaultTheme}>
<div className="App">
<ThemeProvider theme={theme}>
<Tooltip title="This tooltip is customized via overrides in the theme">
<div style={{ marginBottom: "20px" }}>
Hover to see tooltip customized via theme
</div>
</Tooltip>
</ThemeProvider>
<BlueOnGreenTooltip title="This tooltip is customized via styled">
<div style={{ marginBottom: "20px" }}>
Hover to see blue-on-green tooltip customized via styled
</div>
</BlueOnGreenTooltip>
<TextOnlyTooltip title="This tooltip is customized via styled">
<div style={{ marginBottom: "20px" }}>
Hover to see text-only tooltip customized via styled
</div>
</TextOnlyTooltip>
<Tooltip
title="This tooltip is customized via the sx prop"
componentsProps={{
tooltip: {
sx: {
color: "purple",
backgroundColor: "lightblue",
fontSize: "2em"
}
}
}}
>
<div>
Hover to see purple-on-blue tooltip customized via the sx prop
</div>
</Tooltip>
</div>
</ThemeProvider>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Documentation on changes to the theme structure between v4 and v5: https://mui.com/guides/migration-v4/#theme
Tooltip customization examples in the Material-UI documentation: https://mui.com/components/tooltips/#customization
MUI v5 Update
You can customize the Tooltip by overriding the styles in the tooltip slot. There are 3 ways to do that in v5. For reference, see the customization section of Tooltip. More examples of sx prop and createTheme can be seen here and here.
styled()
const ToBeStyledTooltip = ({ className, ...props }) => (
<Tooltip {...props} classes={{ tooltip: className }} />
);
const StyledTooltip = styled(ToBeStyledTooltip)(({ theme }) => ({
backgroundColor: '#f5f5f9',
color: 'rgba(0, 0, 0, 0.87)',
border: '1px solid #dadde9',
}));
sx prop
<Tooltip
title="Add"
arrow
componentsProps={{
tooltip: {
sx: {
bgcolor: 'common.black',
'& .MuiTooltip-arrow': {
color: 'common.black',
},
},
},
}}
>
<Button>SX</Button>
</Tooltip>
createTheme + ThemeProvider
const theme = createTheme({
components: {
MuiTooltip: {
styleOverrides: {
tooltip: {
backgroundColor: 'pink',
color: 'red',
border: '1px solid #dadde9',
},
},
},
},
});
If you want to change text color , font-size ... of Tooltip there is a simple way.
You can insert a Tag inside Title of Martial Ui Tooltip for example :
<Tooltip title={<span>YourText</span>}>
<Button>Grow</Button>
</Tooltip>
then you can style your tag anyhow you want.
check below Example :
This answer is out of date. This answer was written in 2016 for the 0.x versions of Material-UI. Please see this answer for an approach that works with versions 3 and 4.
well, you can change the text color and the element background customizing the mui theme.
color - is the text color
rippleBackgroundColor - is the tooltip bbackground
Example: Using IconButton - but you could you the Tooltip directly..
import React from 'react';
import IconButton from 'material-ui/IconButton';
import MuiThemeProvider from 'material-ui/lib/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/lib/styles/getMuiTheme';
const muiTheme = getMuiTheme({
tooltip: {
color: '#f1f1f1',
rippleBackgroundColor: 'blue'
},
});
const Example = () => (
<div>
<MuiThemeProvider muiTheme={muiTheme}>
<IconButton iconClassName="muidocs-icon-custom-github" tooltip="test" />
</MuiThemeProvider>
</div>
);
You can also pass a style object for the Tooltip (in IconButton it's tooltipStyles) - but these styles will only be applied for the root element.
It's not possible yet to change the label style to make it wrap in multiple lines.
I ran into this issue as well, and want for anyone seeking to simply change the color of their tooltip to see this solution that worked for me:
import React from 'react';
import { makeStyles } from '#material-ui/core/styles';
import Tooltip from '#material-ui/core/Tooltip';
import Button from '#material-ui/core/Button';
import DeleteIcon from '#material-ui/icons/Delete';
const useStyles = makeStyles(theme => ({
customTooltip: {
// I used the rgba color for the standard "secondary" color
backgroundColor: 'rgba(220, 0, 78, 0.8)',
},
customArrow: {
color: 'rgba(220, 0, 78, 0.8)',
},
}));
export default TooltipExample = () => {
const classes = useStyles();
return (
<>
<Tooltip
classes={{
tooltip: classes.customTooltip,
arrow: classes.customArrow
}}
title="Delete"
arrow
>
<Button color="secondary"><DeleteIcon /></Button>
</Tooltip>
</>
);
};
MUI v5 custom component
Building on NearHuscarl's answer using sx, the simplest approach for me was to create a custom component to include the styling plus any other properties you want repeated on each tooltip.
For example, the component could display the tooltips on the bottom with an arrow and a larger font size:
const StyledTooltip = ({ title, children, ...props }) => (
<Tooltip
{...props}
title={title}
placement="bottom"
arrow
componentsProps={{
tooltip: {
sx: {
fontSize: '1.125rem',
},
},
}}
>
{children}
</Tooltip>
);
const Buttons = () => (
<div>
<StyledTooltip title="This is one">
<Button>One</Button>
</StyledTooltip>
<StyledTooltip title="This is two">
<Button>Two</Button>
</StyledTooltip>
</div>
);
Another solution with HtmlTooltip
I Use HtmlTooltip and add arrow: {color: '#f5f5f9',}, for the arrow tooltip style.
And much more to the tooltip style itself.
So I use ValueLabelComponent to control the label and put there a Tooltip from MaterialUI.
Hopes it give another way to edit MaterialUI Tooltip :)
const HtmlTooltip = withStyles((theme) => ({
tooltip: {
backgroundColor: 'var(--blue)',
color: 'white',
maxWidth: 220,
fontSize: theme.typography.pxToRem(12),
border: '1px solid #dadde9',
},
arrow: {
color: '#f5f5f9',
},
}))(Tooltip);
function ValueLabelComponent({ children, open, value }) {
return (
<HtmlTooltip arrow open={open} enterTouchDelay={0} placement="top" title={value}>
{children}
</HtmlTooltip>
);
}
...
...
return (
<div className={classes.root}>
<Slider
value={value}
onChange={handleChange}
onChangeCommitted={handleChangeCommitted}
scale={(x) => convertRangeValueToOriginalValue(x, minMaxObj)}
valueLabelDisplay="auto"
valueLabelFormat={(x) => '$' + x}
ValueLabelComponent={ValueLabelComponent}
aria-labelledby="range-slider"
/>
</div>
);
I used makeStyles() and ended with that:
import React from 'react';
import Grid from '#mui/material/Grid';
import Typography from '#mui/material/Typography';
import Tooltip from '#mui/material/Tooltip';
import InfoOutlinedIcon from '#mui/icons-material/InfoOutlined';
import { makeStyles } from '#material-ui/core/styles';
const styles = makeStyles({
tooltip: {
backgroundColor: '#FFFFFF',
color: '#000000',
border: '.5px solid #999999',
fontSize: '.85rem',
fontWeight: '400'
}
});
const HeaderTooltip = ({ header, tooltip }) =>
<Grid container direction="row" alignItems="center" spacing={1}>
<Grid item>
<Typography variant='h5'>{header}</Typography>
</Grid>
<Grid item>
<Tooltip title={tooltip} classes={{ tooltip: styles().tooltip }}>
<InfoOutlinedIcon />
</Tooltip>
</Grid>
</Grid>
export default HeaderTooltip;
With styledComponent and MUI V5
import styled from 'styled-components';
....
....
<StyledTooltip title={tooltip}>
<IconTextStyle>
{icon}
<Label>{label}</Label>
</IconTextStyle>
</StyledTooltip>
const StyledTooltip = styled((props) => (
<Tooltip classes={{ popper: props.className }} {...props} />
))`
& .MuiTooltip-tooltip {
display: flex;
background-color: #191c28;
border-radius: 4px;
box-shadow: 0px 0px 24px #00000034;
}
`;
I'm created custom Tooltip in the following way
import React from 'react'
import Tooltip from '#material-ui/core/Tooltip'
import ErrorOutlineOutlinedIcon from '#material-ui/icons/ErrorOutlineOutlined'
import {
makeStyles,
createStyles,
withStyles,
} from '#material-ui/core/styles'
import Typography from '#material-ui/core/Typography'
import { Divider, Link, Paper } from '#material-ui/core'
const HtmlTooltip = withStyles(theme => ({
arrow: {
'&::before': {
color: 'white'
}
},
tooltip: {
backgroundColor: '#f5f5f9',
boxShadow: theme.shadows[8],
color: 'rgba(0, 0, 0, 0.87)',
fontSize: 14,
maxWidth: 800,
padding: 0,
},
tooltipPlacementTop: {
margin: '4px 0',
},
}))(Tooltip)
const imageStyles = { root: { color: 'deeppink', height: 20, marginBottom: 0, width: 20 } }
const Image = withStyles(imageStyles)(({ classes }) => (
<ErrorOutlineOutlinedIcon classes={classes} />
))
const useStyles = makeStyles(theme =>
createStyles({
content: {
border: `1px solid ${theme.palette.grey[300]}`,
margin: 0,
minWidth: 600,
padding: 0,
zIndex: 1,
},
contentInner: {
padding: theme.spacing(1)
},
header: {
backgroundColor: 'deeppink',
fontWeight: 'bold',
padding: theme.spacing(1),
}
})
)
export default function CustomTooltip(params) {
const classes = useStyles()
const labelDisplay = params.content
const textDispaly = params.text
return (
<>
{labelDisplay && labelDisplay.length > 20 ? (<HtmlTooltip arrow interactive title={
<Paper className={classes.content}>
<div className={classes.header}>
<Typography color='inherit' variant='body1' style={{color: 'white', fontSize: '20px'}}>
{params.title}
</Typography>
</div>
<Divider />
<div className={classes.contentInner}>
{textDispaly}
</div>
</Paper>}
placement='top'
>
<div style={{ alignItems: 'center', display: 'flex', fontSize: '12px', justifyContent: 'space-between' }}>
{labelDisplay}<Image/>
</div>
</HtmlTooltip>) : (labelDisplay)}
</>
)
}