target pseudo selectors in material ui - css-selectors

I'm wondering if there's a way to target psedo selectors (::before, ::after) in material ui?
For example, in a component like this?
const useStyles = makeStyles((theme) => ({
root: {
textAlign: 'center',
'&::before': {
content: '"blabla"'
},
'&::after': {
content: '"blabla"'
},
':before': {},
after: {}
}
}));
function App(props) {
const classes = useStyles();
return (
<Typography
className={{ root: classes.root, before: classes.before, after: classes.after }}>
{props.children}
</Typography>
);
}

I have created this sandbox project, you can check, things are working fine or correct me if I am missing something to understand your problem
import React from "react";
import { makeStyles } from "#material-ui/core/styles";
import Typography from "#material-ui/core/Typography";
const useStyles = makeStyles(theme => ({
root: {
textAlign: "center",
"&::before": {
content: '"-"'
},
"&::after": {
content: '"-"'
}
}
}));
export default function App(props) {
const classes = useStyles();
return (
<Typography className={classes.root} {...props}>
Hello
</Typography>
);
}
I think you are using the className props in a wrong way, you have to pass the string, not an object.
classes props expect an object, we generally use classes props on the component which have exposed class names to override their inner styles, for example in case of Typography Component you can override root element style like this.
export default function App(props) {
const classes = useStyles();
return (
<Typography classes={{ root: classes.root }} {...props}>
Hello
</Typography>
);
}
so classes and classNames are two different things in Material-UI, but sometimes(when you want to apply the style to root element of component) both provide the same solution.
I have created one more Sandbox project with the second solution

Related

just declaring useStyles in a Mui-React wrapper component, produces strange behaviors

I'm using mui makeStyles in all my components.
But when I try to use it in a wrapper component, I get undesired behavior
The code that I'm using is this:
import Box from '#mui/material/Box';
import React from 'react';
import NavBar from './NavBar';
import SwipeableLeftDrawer from './SwipeableLeftDrawer';
import { makeStyles } from '#mui/styles';
const useStyles = makeStyles((theme) => ({
text: {
marginTop: 0
}
}));
const WrapperComponent = ({ render }) => {
// const classes = useStyles(); // If I uncomment this line, I start to have problems
const [ drawerOpen, setDrawerOpen ] = React.useState(false);
return (
<Box>
<SwipeableLeftDrawer
open={drawerOpen}
setDrawerOpen={setDrawerOpen}
drawerWith={'10em'}
//
/>
<Box
sx={{
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between',
width: '100vw',
height: '100vh'
}}
>
<NavBar setOpenDrawer={setDrawerOpen} /> // <=== HERE, SOME STYLINGS CEASE TO WORK
<Box>{render()}</Box> // here, I render the wrapped component
...
...
This is what I have now,
If I just declare the constant classes = useStyles, even without using it, I get this:
Can somebody tell me what am I missing here?
Thanks in advance
Rafael
don't use makeStyle in mui v5 style by using sx props

How to override anchor <a> element in material ui v3?

I have tried to override the in typography with
root: {
'&a':{
color: '#FF6600'
},
},
but didn't work any suggestions ?
There are multiple ways to change the color(style) of Material-UI <Typography /> locally.
Mostly been used options would be considered as:
Add style based on the provided CSS API - refer to MUI Typography API document
Override style using the nesting selector for elements and classes - you can find the details inside the browser dev tools
import React from "react";
import "./styles.css";
import { makeStyles } from "#material-ui/core/styles";
import { Typography } from "#material-ui/core";
const useStyles = makeStyles(theme => ({
option1: {
color: "red"
},
option2: {
"&.MuiTypography-root": {
color: "blue"
}
}
}));
export default function App() {
const classes = useStyles();
return (
<div className="App">
<Typography
variant="h5"
component="h5"
classes={{ root: classes.option1 }}
>
Use CSS API with attribute: root
</Typography>
<Typography variant="h5" component="h5" className={classes.option2}>
Use nesting selector of className: MuiTypography-root
</Typography>
</div>
);
}

How to overwrite tags with useStyles() in React with MUI

I'm trying to overwrite the Link tag of React-Router with makeStyles() to remove the link decoration. Am I using makeStyles incorrectly? The default text underline is still showing.
const useStyles = makeStyles((theme) => ({
root: {
display: "flex",
},
Link: {
textDecoration: "none",
},
}));
The makeStyles function will not override any Mui-related style definitions. The usage of the makeStyles is to give you an easy way to create new classes and then use them.
For example:
const useStyles = makeStyles(theme => ({
myLayout: {
width: "auto",
background: "red"
}
}));
const classes = useStyles();
...
<div className={classes.myLayout}>
If you want to override entire definition of Mui component, you will need to know which component it is, what it's internal Mui name, and then you can use the createMuiTheme for that:
const muiTheme = createMuiTheme({
overrides: {
MuiLink: {
root: {
textDecoration: "none"
}
},
}
});
...
<MuiThemeProvider theme={muiTheme}>
<Link />
</MuiThemeProvider>
If you want to change only one specific link (and not to override the style definitions of all the links in your website) you can use the makeStyles and then use the specific class in the <Link /> component:
const useStyles = makeStyles(theme => ({
noDecoration: {
textDecoration: "none"
}
}));
const classes = useStyles();
...
<Link className={classes.noDecoration}>
Note - if you are using the <Link /> component from react-router-dom - this is not a MUI component, so it will not have any MUI related classnames. You can check the example here on how to design the router's link based on the MUI components.

Material UI: Display sub-element on hover of parent

When the user hovers over a Card component, I'd like to show a button on that component that is otherwise invisible. In CSS, I'd do something like this:
.card:hover my-button {
display: block;
}
How do I replicate this in the "Material-UI" way?
All the Material-UI tips I found so far suggest something like this to add hover styling, but this applies the styles to the component that is being hovered over and not a different one.
'&:hover': {
background: 'blue'
}
You can do the exact same thing with CSS using the createMuiTheme:
export const theme = createMuiTheme({
overrides: {
// For label
MuiCard: {
root: {
"& .hidden-button": {
display: "none"
},
"&:hover .hidden-button": {
display: "flex"
}
}
}
}
});
Give the Button inside your Card the className hidden-button and you will get the same thing that you want.
Check it here: https://codesandbox.io/s/mui-theme-css-hover-example-n8ou5
It is not specific to Material UI but a react specific thing. you need a state variable to show/hide your button.
const App = () => {
const [show, setShow] = useState(false);
return (
<Card
onMouseOver={() => setShow(true)}
onMouseOut={() => setShow(false)}>
<CardBody>
// some content
{show && <Button>Click</Button>}
</CardBody>
</Card>
);
}
If you want to define this purely inside of a styled component instead of using either of createMuiTheme or makeStyles, then try the following.
We will give an id to each child component and reference them when defining the behaviour to implement when we hover over the parent component:
const NameCellBox = styled(Box)(({ theme }) => ({
...other styles,
"&:hover #cellBoxLengthTypo": {
display: "none",
},
"&:hover #cellBoxContentTypo": {
display: "inline-block",
},
}));
const CellBoxLengthTypo = styled(Typography)(({ theme }) => ({
fontFamily: theme.typography.fontFamily,
fontSize: theme.typography.h5.fontSize,
}));
const CellBoxContentTypo = styled(Typography)(({ theme }) => ({
display: "none",
fontFamily: theme.typography.fontFamily,
fontSize: theme.typography.h5.fontSize,
}));
const items: string[] = ["andrew", "barry", "chris", "debbie"];
return (
<>
<NameCellBox>
<CellBoxLengthTypo id="cellBoxLengthTypo">+{items.length}</CellBoxLengthTypo>
<CellBoxContentTypo id="cellBoxContentTypo">{items.join(", ")}</CellBoxContentTypo>
</NameCellBox>
</>
);
Found it useful for updating a DataGrid cell in Material UI when hover or other event fired.
I faced this problem today and after I discussed it with my mentor I made this result and it worked well for me. but first, let me tell you the disadvantage of using eventListener like onMouseEnter & on MouseLeave that it will cause so many renders.
I gave the (parent component) a movie-card class and the (child component) a movie-card-content class like the following
// movie-card.css
.movie-card-content {
opacity: 0;
}
.movie-card:hover .movie-card-content {
opacity: 1;
}
MUI allows you to add className prop so I gave the proper classNames
//MovieCard.jsx (component)
import "./movie-card.css";
function MovieCard () {
return (
<Card className="movie-card">
<CardContent className="movie-card-content">...<CardContent>
</Card>
);
}
and that's it 😉
import {
makeStyles
} from '#material-ui/core'
const useStyles = makeStyles(() => ({
root: {
"& .appear-item": {
display: "none"
},
"&:hover .appear-item": {
display: "block"
}
}
}))
export default function MakeTextAppearOnHover() {
const classes = useStyles()
return (
<div className = { classes.root }>
Hello world
<span className = 'appear-item' >
Appearing text Go
</span>
</div>
)
}
This is a material UI example that displays the sub-element on hover of the parent.
I also noticed that using some of the examples above, when using Material UI's makeStyles, the overlay item was flickering a lot when clicked. This solution below does not flicker when sub-element is clicked.
import React from "react"
import { Card, CardActionArea, CardContent, CardMedia } from "#material-
ui/core";
import { makeStyles } from "#material-ui/core/styles";
const useStyles = makeStyles(theme => ({
card: {
// some styles
},
cardAction: {
position: "relative"
},
media: {
// some styles
},
overlay: {
position: "absolute",
top: "85px"
}
}));
const App = () => {
const classes = useStyles();
const [show, setShow] = React.useState(false);
const handleMouseOver = () => {
setShow(true);
};
const handleMouseOut = () => {
setShow(false);
};
return (
<Card>
<CardActionArea
onMouseOver={handleMouseOver}
onMouseOut={handleMouseOut} className={classes.card} >
<CardMedia className={classes.media} component="img" >
// some content
</CardMedia>
<CardContent className={classes.overlay} style={{ display: show ?
'block' : 'none' }>
// some content
</CardContent>
</CardActionArea>
</Card>
);
}

Reference to theme's primary color instead of a specific color in MUI

Using ReactJS and MUI, I have a project in which I have changed the theme colors.
const newTheme = getMuiTheme({
fontFamily: 'Roboto, sans-serif',
palette: {
primary1Color: cyan500,
primary2Color: cyan700,
primary3Color: grey400,
accent1Color: amberA400,
accent2Color: grey100,
accent3Color: grey500,
textColor: darkBlack,
alternateTextColor: white,
canvasColor: white,
borderColor: grey300,
disabledColor: fade(darkBlack, 0.3),
pickerHeaderColor: cyan500,
clockCircleColor: fade(darkBlack, 0.07),
shadowColor: fullBlack,
},
});
// App class
render() {
return(
<ThemeProvider theme={newTheme}>
<Project />
</ThemeProvider>
)
}
Everything works as expected. Certain components, like buttons have the ability to set the color based on the primary prop. However, I have a component that uses an icon that needs the primary color. I can import the color and set it directly:
import React from 'react';
import ActionLock from 'material-ui/svg-icons/action/lock';
import {cyan500} from 'material-ui/styles/colors';
export default class LockIcon extends React.Component {
render() {
return(
<ActionLock color={cyan500} />
)
}
}
Is there some way to reference the theme's primary color, rather than setting the color in each component individually? Something like:
import React from 'react';
import ActionLock from 'material-ui/svg-icons/action/lock';
import {primary1Color} from 'somewhere';
export default class LockIcon extends React.Component {
render() {
return(
<ActionLock color={primary1Color} />
)
}
}
If you're using React v16.8.0 and Material-UI v3.5.0 or greater, you can utilize the useTheme() hook:
import { useTheme } from '#material-ui/core/styles';
function LockIcon = () => {
const theme = useTheme();
return (
<ActionLock color={theme.palette.primary1Color} />
}
Yes you have!
using muiThemeable..
import muiThemeable from 'material-ui/styles/muiThemeable';
class LockIcon extends React.Component {
render() {
return(
<ActionLock color={this.props.muiTheme.palette.primary1Color} />
)
}
}
export default muiThemeable()(LockIcon)
from material-ui docs
Adding how to access theme colors in material-ui v1.0.0 (currently beta) Using withTheme component.
Also check the following Example.
import React, {Component} from 'react';
import { withTheme } from 'material-ui/styles';
class WithThemeExample extends Component {
render() {
const { theme } = props;
const {primary, secondary} = theme.palette.text;
return (
<div>
<div style={{color: primary}}>Hi in Primary color</div>
<div style={{color: secondary}}>Bye in Secondary color</div>
</div>
);
}
}
export default withTheme()(WithThemeExample);
If you're using system properties, you can define a string path of the Palette object to the color value like below:
<Box sx={{ color: "primary.main" }}>primary.main</Box>
<Box sx={{ color: "secondary.main" }}>secondary.main</Box>
<Box sx={{ color: "error.main" }}>error.main</Box>
<Box sx={{ color: "warning.main" }}>warning.main</Box>
<Box sx={{ color: "info.main" }}>info.main</Box>
<Box sx={{ color: "success.main" }}>success.main</Box>
<Box sx={{ color: "text.primary" }}>text.primary</Box>
<Box sx={{ color: "text.secondary" }}>text.secondary</Box>
<Box sx={{ color: "text.disabled" }}>text.disabled</Box>
The above is the same as:
<Box sx={{ color: theme => theme.palette.primary.main }}>primary.main</Box>
<Box sx={{ color: theme => theme.palette.secondary.main }}>secondary.main</Box>
<Box sx={{ color: theme => theme.palette.error.main }}>error.main</Box>
<Box sx={{ color: theme => theme.palette.warning.main }}>warning.main</Box>
<Box sx={{ color: theme => theme.palette.info.main }}>info.main</Box>
<Box sx={{ color: theme => theme.palette.success.main }}>success.main</Box>
<Box sx={{ color: theme => theme.palette.text.primary }}>text.primary</Box>
<Box sx={{ color: theme => theme.palette.text.secondary }}>text.secondary</Box>
<Box sx={{ color: theme => theme.palette.text.disabled }}>text.disabled</Box>
The example using the callback is more verbose but is type-safe, the shorter one with only string is quicker and good when prototyping, but you may want to store the string in a constant to prevent any typo errors and help the IDE refactor your code better.
Live Demo
Ok if you are using material-ui version greater than 4, then the above solution might not work for you. Follow the below's code
import { withTheme } from '#material-ui/core/styles';
function DeepChildRaw(props) {
return <span>{`spacing ${props.theme.spacing}`}</span>;
}
const DeepChild = withTheme(DeepChildRaw);
Reference: https://material-ui.com/styles/advanced/
With react hooks, now you don't need to warp component in withTheme, just use useTheme:
import { useTheme } from '#material-ui/core/styles';
export default function MyComponent() {
const theme = useTheme();
return <span>{`spacing ${theme.spacing}`}</span>;
}
MUI V5
For the users of MUI v5, you can specify a function inside the sx css style directly, ex:
<Box sx={{ color: (theme) => theme.palette.primary1Color }} />
You can use the useTheme() hook and access the colors like the example below.
There are also some other color variants as well.
Mui 5:
import * as React from 'react';
import PropTypes from 'prop-types';
import { NavLink } from "react-router-dom";
import { useTheme } from "#mui/material/styles";
function VinNavLink(props) {
const theme = useTheme();
return (
<NavLink {...props} style={({ isActive }) => isActive ? { textDecoration: "underline", color: theme.palette.primary.main} : undefined}>{props.children}</NavLink>
);
}
export default VinNavLink;

Resources