Failed to override styles with classes in material-ui - css

I was implementing a table with TableRow component from material-ui, which has a property called "selected". Whenever "selected" is true, a pink background-color(from the default theme) is applied for it.
I was trying to change this default pink color, according to the docs, i chose to override the css classes like:
const styles = theme => ({
rowSelected: {
backgroundColor: theme.palette.grey[700]
}
})
class CustomTableRow extends React.Component {
// basic component logic
render() {
const {classes, className, style } = this.props;
<TableRow
key={key}
component="div"
selected={true}
hover={true}
className={className}
classes={{ selected: classes.rowSelected}}
style={style}
>
// some children
</TableRow>
}
export default withStyles(styles, { withTheme: true })(CustomTableRow);
But this didn't work, which was very confusing. Because i had succeeded to do the same thing somewhere else for a Drawer component with the same method above.
I debugged every css properties with Chrome Dev Tools. What i am suspecting most now is, the pink color applied on this component with this way below:
.MuiTableRow-root.Mui-selected, .MuiTableRow-root.Mui-selected:hover {
background-color: rgba(245, 0, 87, 0.16);
And my custom class style had lower precedence than this one, which was greyed out.
UPDATE1:
My project is too big, i don't know how to simplify it for codesandbox.io.
Maybe we can check the material-ui source code directly, TableRow Source Code.
What i was doing is to override this css declaration in root
'&$selected, &$selected:hover': {
backgroundColor: fade(theme.palette.secondary.main, theme.palette.action.selectedOpacity),
},
by passing in another selected declaration below. I realized it's because this &$selected, &$selected:hover is not normally css, even if i copy this into rowSelected, it doesn't work either.
UPDATE2:
I managed to override that backgroundColor, with '!important' keyword:
const styles = theme => ({
rowSelected: {
backgroundColor: theme.palette.grey[700] + " !important",
}
})
I don't know whether this is one ideal solution. This clearly shows the problem is about css classes precedence. So how to override that already defined backgroundColor in class root with class selected.
Some help please, thank you.

To provide specifity for selected class you can apply the $selected and $selected:hover classes to your overrides like below
const styles = theme => ({
rowSelected: {
"&$selected, &$selected:hover": {
backgroundColor: theme.palette.grey[800]
}
}
})
Sample demo

Related

How to style Material-UI's BottomNavigationAction, so the selected icon is a different color?

I need some help with this problem I'm having with Material-UI styled components
I'm trying to create a BottomNavigation bar on react using Material-UI v5. I want that the icon of the selected option in the bar shows a specific color, let's say red (#f00) and the not-selected icons show green (#00f), for this I'm using the styled function to generate a custom-themed component for BottomNavigationAction, following the guidelines on the documentation: styled(). The problem: For the selected button, the icon is not grabbing the correct color and is showing the default one. At this point I'm not sure if I'm using the styled function wrong or is something super obvious I'm not seeing. Thanks in advance for any advice!
PS: I don't have enough reputation to post the image directly, sorry for that
The BottomNavigation is defined as follows:
const BottomNav = () => {
return(
<BottomNavigation
showLabels
value={value}
onChange={(event, newValue) => {setValue(newValue)}}
>
<TabBarButton
id='Home'
label='Home'
icon= {home_icon? <AiFillHome size = "30" />: <AiOutlineHome size='30'/> }
onClick={
(value)=>{
iconHandler(value.currentTarget.id)
}
}
/>
<TabBarButton
id='Documentos'
label='Documentos'
icon= {documentos_icon? <RiEditBoxFill size='30'/>: <RiEditBoxLine size='30'/>}
onClick={
(value) =>
iconHandler(value.currentTarget.id)
}
}
/>
</BottomNavigation>
);
}
To define TabBarButton I firstly tried defining the component like this:
import {BottomNavigation, BottomNavigationAction} from "#mui/material";
import { styled} from '#mui/system';
// Styled BottomNavigationAction
const TabBarButton = styled(BottomNavigationAction)({
root: {
color: '#f00',
},
selected: {
color: '#0f0',
}
});
But the rule names: root and selected didn't work, resulting in the default colors being applied:
first-try-bottom-navigation-image
So I changed them to the Global Class instead : BottomNavigationAction CSS :
// Styled BottomNavigationAction
const TabBarButton = styled(BottomNavigationAction)({
color: '#0f0',
'.Mui-selected':{
color: '#f00',
}
});
Which worked with the not-selected icon and the labels:
second-try-bottom-navigation-image
But the selected icon 'Home' is still using the default colors, I tried using a variation of the answer provided on this post Bottom Navigation Material UI Override
// Styled BottomNavigationAction
const TabBarButton = styled(BottomNavigationAction)({
color: '#0f0',
'.Mui-selected, svg':{
color: '#f00',
}
});
But this affects both icons resulting in :
third-try-bottom-navigation-image
I think TabBarButton need to add '&.Mui-selected' selector to have the styles attached to itself correctly, otherwise with '.Mui-selected' the rules only apply to nested elements:
Tested the example on: stackblitz
// Styled BottomNavigationAction
const TabBarButton = styled(BottomNavigationAction)({
color: 'royalblue',
'&.Mui-selected': {
color: 'crimson',
},
});

Material UI 5 class name styles

I migrated from Mui 4 to 5 and wonder how to use class names. If I want to apply certain styles to just one component there is the SX property. However, I'm struggling with using the same class for multiple components. In v4 my code looked like this:
export const useStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
padding: theme.spacing(1),
margin: 'auto',
},
})
)
I could import this useStyles hook in any component and use it like this:
const classes = useStyles()
...
<div className={classes.root}>...</div>
This docs say, that I can 'override styles with class names', but they don't tell how to do it:
https://mui.com/customization/how-to-customize/#overriding-styles-with-class-names
Do I have to put these styles in an external CSS file?
.Button {
color: black;
}
I would rather define the styles in my ts file.
I also found this migration guide:
https://next.material-ui.com/guides/migration-v4/#migrate-makestyles-to-emotion
I don't like approach one, because using this Root wrapper, it is inconvenient to apply a class conditionally. (Especially for typescript there is some overhead) Approach two comes with an external dependency and some boilerplate code.
Ideally I would use styles like this, perhaps with one rapper function around the styles object:
export const root = {
padding: theme.spacing(1),
margin: 'auto',
}
<div className={root}>...</div>
Of course, the last approach doesn't work, because className wants a string as input. Does anybody know an alternative with little boilerplate code?
I suggest you take a look at emotion's documentations for details. The sx prop is actually passed to emotion.
You can do something like this:
const sx = {
"& .MuiDrawer-paper": {
width: drawerWidth
}
};
<Drawer sx={sx}/>
Equivalent to MUI v4
const useStyles = makeStyles({
drawerPaper: {
width: drawerWidth,
}
});
const classes = useStyles();
<Drawer
classes={{
paper: classes.drawerPaper,
}}
/>
Answering your exact question, there are use cases (I think yours is not one of them and you should use styled components) however for those like me who stumble upon it and want a "exact answer to this question" and not a "do this instead", this is how you achieve to retrieve the class names.
This is so far undocumented.
For functional components, using emotion, here an use case where you have a 3rd party component that expects, not one, but many class names, or where the className property is not where you are meant to pass the property.
import { css, Theme, useTheme } from "#mui/material/styles";
import { css as emotionCss } from "#emotion/css";
const myStyles = {
basicClass: {
marginLeft: "1rem",
marginRight: "1rem",
paddingLeft: "1rem",
paddingRight: "1rem",
},
optionClass: (theme: Theme) => ({
[theme.breakpoints.down(theme.breakpoints.values.md)]: {
display: "none",
}
})
}
function MyComponent() {
cons theme = useTheme();
// first we need to convert to something emotion can understand
const basicClass = css(myStyles.basicClass);
const optionClass = css(myStyles.optionClass(theme));
// now we can pass to emotion
const basicClassName = emotionCss(basicClass.styles);
const optionClassName = emotionCss(optionClass.styles);
return (
<ThirdPartyComponent basicClassName={basicClassName} optionClassName={optionClassName} />
)
}
When you have a Class Component, you need to use the also undocumented withTheme from #mui/material/styles and wrap your class, if you use the theme.
WHEN IT IS NOT AN USE CASE
When your component uses a single className property just use styled components.
import { styled } from "#mui/material/styles";
const ThrirdPartyStyled = styled(ThirdPartyComponent)(({theme}) => ({
color: theme.palette.success.contrastText
}))
Even if you have dynamic styles
import { styled } from "#mui/material/styles";
interface IThrirdPartyStyledExtraProps {
fullWidth?: boolean;
}
const ThrirdPartyStyled = styled(ThirdPartyComponent, {
shouldForwardProp: (prop) => prop !== "fullWidth"
})<IThrirdPartyStyledExtraProps>(({theme, fullWidth}) => ({
color: theme.palette.success.contrastText,
width: fullWidth ? "100%" : "auto",
}))
Even if each one has some form of custom color, you just would use "sx" on your new ThrirdPartyStyled.
When you are just trying to reuse a style around (your use case)
const myReusableStyle = {
color: "red",
}
// better
const MyStyledDiv = styled("div")(myReusableStyle);
// questionable
const MySpanWithoutStyles = styled("span")();
// better
const MyDrawerStyled = styled(Drawer)(myReusableStyle);
function MyComponent() {
return (
<MyStyledDiv>
questionable usage because it is less clean:
<MySpanWithoutStyles sx={myReusableStyle}>hello</MySpanWithoutStyles>
<MySpanWithoutStyles sx={myReusableStyle}>world</MySpanWithoutStyles>
these two are equivalent:
<MyDrawerStyled />
<Drawer sx={myReusableStyle} />
</MyStyledDiv>
)
}
Now what is "presumably" cool about this is that your style, is just an object now, and you can just import it and use it everywhere without makeStyles or withStyles, supposedly an advantage, even when to be honest, I have never used that of exporting/importing around; the code seems a bit cleaner nevertheless.
You seem to want to use it so all you do is.
export const myStyles {
// your styles here
}
because this object is equivalent in memory, and it is always the same object, something that is easier to mess up with styles, it should be as effective or even more than your hook, theoretically (if it re-renders often even when setup may be longer), which stores the same function in memory but returns a new object every time.
Now you can use those myStyles everywhere you deem reasonable, either with styled components or by assigning to sx.
You can further optimize, say if it's always a div that you use that is styled the same way, then the styled component MyStyledDiv should be faster, because it is the same and done each time. How much faster is this? According to some sources 55% faster, to me, it is taking 4 weeks of refactor and the JSS compatibility with emotion is bad, all mixed with SSR is making everything unusable and slow and broken, so let's see until then when the whole is refactored.
Here is a pattern that I've found useful in MUI 5. It allows you to keep style definitions in the same file but isolated, & avoids repeated function calls for every CSS property where you need to access your theme (e.g. width: ({ spacing }) => spacing(12))). It also feels similar to MUI's native CSS API.
Create a function that takes your theme as an argument & returns an object of named style groups. Then reference those groups directly in your sx props. This also allows for the use of classNames in a way similar to Material-UI 4.
import { useTheme } from '#mui/material';
import clsx from 'clsx';
export const NavItem = (props) => {
// Bring in style groups
const sx = styles(useTheme());
// Define classNames
const classNames = clsx({
isActive: props.isActive
});
return (
{/* Use classNames and style groups */}
<ListItemButton className={classNames} sx={sx.button}>
<ListItemAvatar sx={sx.avatar}>{props.icon}</ListItemAvatar>
<ListItemText>{props.label}</ListItemText>
</ListItemButton>
);
}
// Define style groups
function styles(theme) => {
return {
button: {
paddingX: 6,
'&.isActive': {
backgroundColor: theme.palette.secondary.light
}
},
avatar: {
'.isActive &': {
border: '2px solid green'
}
}
};
}
I'm in the same boat, about six months behind, i.e., starting to make the transition to v5 from v4 now... Just when I thought I had a handle on it all!
Having read this post and trying a few things out, I was able to replicate the ability to re-use a chunk of css. I'm a big fan of what used to be the overrides prop; that feature hasn't gone away, it's just under a different prop (loosely speaking). Regardless, I mention it because it provides access to what I like a lot about css: selectors.
To hit all MUI-Drawers my pref is for whatever the new overrides is. For targeted reuse of css I like the following:
import { reuseThisCss } from 'sharedCss';
export default styled(Drawer)(({ theme, ownerState }) => {
...
return {
'& .MuiDrawer-paper': {
boxShadow: xxl,
border: 'none',
'& .MuiListItemText-root': reuseThisCss,
},
};
export default ThisSpecificDrawerVariant;
Note: The focus is not on using styled (It's not my goto approach).
The css in the return value is the equivalent to the following css: .MuiDrawer-paper .MuiListItemText-root {...}.
This says, "select all .MuiListItemText-root under the .MuiDrawer-paper parent. If I want to optimize the render, while increasing the dependency on a specific hierarchy, I'll specify/expand on the selector that much more with whatever lies between the .MuiDrawer-paper and MuiListItemText-root. For instance, in my case:
...
return {
'& .MuiDrawer-paper': {
boxShadow: xxl,
border: 'none',
'& > a > li > div > .MuiListItemText-root': reuseThisCss,
},
};
Finally, per a question in the comments, generally this will not prevent a nested application of the style. In my experience, marking each level with a className is useful. I only "mark" the element that signals the start of a new level. So, if it were Drawer in the above example, I would start the css selector with .MUI-Drawer.level-3. The rest of css remains the same.
I still have not figured out if whether setting the className dynamically remains a performant and sufficiently flexible goto... TBD.
If you are using makeStyles or withStyles to provide CSS class, you can follow the instruction below.
CSS overrides created by makeStyles

How can I dynamically set style of a mapped element without using inline styling?

I'm coding a React function with parent component containing an array of objects:
let const ingredients = [
{name:"lettuce",color:"green"},
{name:"tomato",color:"red"}
]
...
In a child component, there is a map function that breaks down an array to single items to be displayed in a div.
What is the best practice for defining CSS styling for an object className:"name" to set backgroundColor: {ingredient.color};? I'm trying to avoid manual entry of the entire set of key/values of 'ingredients', to allow updating the object without breaking the code.
I'm currently using inline styling, which I have been advised against. Currently using:
let burg = props.toppings.map((item) => {
const divColor = {backgroundColor: item.color};
return (<div style={divColor}>{item.name}</div>)
Inline style is bad when you have other solution to do what you want. Here, you have a string that is the color (red, green, etc.) so you could write a css class for every color, but that is of course a really bad idea. Inline style is the good way to do it here.
I would suggest setting the class of the div instead of the style. That way you can change the look without resorting to inlining the style.
You could create a css class for lettuce with the background color green, instead of using the item.color you'd set class={ item.name }
You can use this way.
css can be more handy if you use scss
// css
.color-green {
color: green;
}
.color-red {
color: red;
}
import React from "react";
import "./styles.css";
const ingredients = [
{ name: "lettuce", color: "green" },
{ name: "tomato", color: "red" }
];
const Vegetable = ({ color, text }) => {
return (
<p>
this is <span className={`color-${color}`}>{text}</span> color{" "}
</p>
);
};
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{ingredients.map((item, index) => {
return <Vegetable key={index} color={item.color} text={item.name} />;
})}
</div>
);
}

Apply style to ButtonBase in a Tab component

I am trying to figure out Material UI style overriding with a nested component. Say I want to increase bottom border height on a active Tab. This border is applied by the underlying ButtonBase.
Here is the style definition:
const useStyles = makeStyles(theme => ({
root: {
// an example brutal overriding, not clean, I'd like a better approach for the button
"& .MuiSvgIcon-root": {
marginRight: "8px"
}
},
// override Tab
tabWrapper: {
flexDirection: "row"
},
tabSelected: {
color: theme.palette.primary.main
},
tabLabelIcon: theme.mixins.toolbar, // same minHeight than toolbar
// TODO override buttonBase ???
// ...
}));
An example usage:
<Tab
value="/"
classes={{
wrapper: classes.tabWrapper,
selected: classes.tabSelected,
labelIcon: classes.tabLabelIcon
}}
icon={
<React.Fragment>
<DashboardIcon />
</React.Fragment>
}
label="Home"
// TODO: is this the expected syntax? TypeScript is not happy with this prop...
buttonBaseProps={{ classes: {} }}
/>
I have no idea how to define the ButtonBase classes in this example.
How should I define my props to override the ButtonBase style?
Edit: doc is here https://material-ui.com/api/tab/, the last section describe the inheritance process but the documentation is very terse.
Edit 2: the example use case is bad as you should override ".MuiTabs-indicator" to increase the bottom border height (it's actually an additional span not a border) but the question stands. Imagine that I want to change the ButtonBase background-color for example.
So as it turns out, There is no separate ButtonBase component inside the Tab component. So you won't find prop called buttonBaseProps. The tab itself is rendered as the button component.
Whatever style you wanna pass, pass it to the root inside classes. See below
<Tab classes={{
root: classes.customButtonBaseRoot,
wrapper: classes.tabWrapper,
selected: classes.tabSelected,
labelIcon: classes.tabLabelIcon
}}
/>
https://codesandbox.io/s/apply-style-to-buttonbase-in-a-tab-component-izgj5

Override Material UI Tab Indicator Emotion Styled

Trying to figure out how to override the styles of the tabs indicator using styled from Emotion. I am not sure how to access nested classes. This is what I have, but it isn't getting me there:
const StyledTabs = styled(Tabs)(
{
classes: {
indicator: {
background: 'black',
},
},
}
);
Any help would be awesome!
There are a couple issues. styled from Emotion only supports generating a single class name per usage. It doesn't provide any support for the classes: {indicator: {styles}} structure in your example.
Below is a syntax that allows you to use styled to provide a class name for the "indicator" class of Tabs:
const StyledTabs = styled(({ className, ...other }) => {
return <Tabs {...other} classes={{ indicator: className }} />;
})({
backgroundColor: "black"
});
However, this does not work completely robustly because the <style> element for the Emotion styles does not consistently occur after the <style> elements from JSS (used for Material-UI's styling) in the <head> of the document. I'm not sure how to alter the insertion point for Emotion's styles, but you can read here about how to change the insertion point for JSS. I've included this approach in my sandbox below.
Here's a sandbox that shows this working:
Another syntax option is the following which will allow you to control more than one Tabs class:
const StyledTabs = styled(({ className, ...other }) => {
return <Tabs {...other} classes={{ root: className, flexContainer: "flexContainer", indicator: "indicator" }} />;
})({
"& .indicator": {
background: "black"
},
"& .flexContainer": {
flexDirection: "row-reverse"
}
});

Resources