score:86
Below is an example of the correct syntax for v4 ("& $addIcon"
nested within &:hover
). Further down are some v5 examples.
import * as React from "react";
import { render } from "react-dom";
import { Grid, makeStyles } from "@material-ui/core";
import AddIcon from "@material-ui/icons/Add";
const useStyles = makeStyles(theme => ({
outerDiv: {
backgroundColor: theme.palette.grey[200],
padding: theme.spacing(4),
'&:hover': {
cursor: 'pointer',
backgroundColor: theme.palette.grey[100],
"& $addIcon": {
color: "purple"
}
}
},
addIcon: (props: { dragActive: boolean }) => ({
height: 50,
width: 50,
color: theme.palette.grey[400],
marginBottom: theme.spacing(2)
})
}));
function App() {
const classes = useStyles();
return (
<Grid container>
<Grid item className={classes.outerDiv}>
<AddIcon className={classes.addIcon} />
</Grid>
</Grid>
);
}
const rootElement = document.getElementById("root");
render(<App />, rootElement);
Related documentation and answers:
- https://cssinjs.org/jss-plugin-nested?v=v10.0.0#use-rulename-to-reference-a-local-rule-within-the-same-style-sheet
- how to use css in JS for nested hover styles, Material UI
- Material UI: affect children based on class
- Advanced styling in material-ui
For those who have started using Material-UI v5, the example below implements the same styles but leveraging the new sx
prop.
import Grid from "@mui/material/Grid";
import { useTheme } from "@mui/material/styles";
import AddIcon from "@mui/icons-material/Add";
export default function App() {
const theme = useTheme();
return (
<Grid container>
<Grid
item
sx={{
p: 4,
backgroundColor: theme.palette.grey[200],
"&:hover": {
backgroundColor: theme.palette.grey[100],
cursor: "pointer",
"& .addIcon": {
color: "purple"
}
}
}}
>
<AddIcon
className="addIcon"
sx={{
height: "50px",
width: "50px",
color: theme.palette.grey[400],
mb: 2
}}
/>
</Grid>
</Grid>
);
}
Here's another v5 example, but using Emotion's styled
function rather than Material-UI's sx
prop:
import Grid from "@mui/material/Grid";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import AddIcon from "@mui/icons-material/Add";
import styled from "@emotion/styled/macro";
const StyledAddIcon = styled(AddIcon)(({ theme }) => ({
height: "50px",
width: "50px",
color: theme.palette.grey[400],
marginBottom: theme.spacing(2)
}));
const StyledGrid = styled(Grid)(({ theme }) => ({
padding: theme.spacing(4),
backgroundColor: theme.palette.grey[200],
"&:hover": {
backgroundColor: theme.palette.grey[100],
cursor: "pointer",
[`${StyledAddIcon}`]: {
color: "purple"
}
}
}));
const theme = createTheme();
export default function App() {
return (
<ThemeProvider theme={theme}>
<Grid container>
<StyledGrid item>
<StyledAddIcon />
</StyledGrid>
</Grid>
</ThemeProvider>
);
}
And one more v5 example using Emotion's css prop:
/** @jsxImportSource @emotion/react */
import Grid from "@mui/material/Grid";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import AddIcon from "@mui/icons-material/Add";
const theme = createTheme();
export default function App() {
return (
<ThemeProvider theme={theme}>
<Grid container>
<Grid
item
css={(theme) => ({
padding: theme.spacing(4),
backgroundColor: theme.palette.grey[200],
"&:hover": {
backgroundColor: theme.palette.grey[100],
cursor: "pointer",
"& .addIcon": {
color: "purple"
}
}
})}
>
<AddIcon
className="addIcon"
css={(theme) => ({
height: "50px",
width: "50px",
color: theme.palette.grey[400],
marginBottom: theme.spacing(2)
})}
/>
</Grid>
</Grid>
</ThemeProvider>
);
}
score:2
Possibly an obvious point, but just to add to the answer above: if you are referencing a separate className, don't forget that you also need to create it in the makeStyles hook or else it won't work. For instance:
const useStyles = makeStyles({
parent: {
color: "red",
"&:hover": {
"& $child": {
color: "blue" // will only apply if the class below is declared (can be declared empty)
}
}
},
// child: {} // THIS must be created / uncommented in order for the code above to work; assigning the className to the component alone won't work.
})
const Example = () => {
const classes = useStyles()
return (
<Box className={classes.parent}>
<Box className={classes.child}>
I am red unless you create the child class in the hook
</Box>
</Box>
)
}
score:3
This denotes the current selector which is the parent component:
'&': { /* styles */ }
This means the parent component in hover state:
'&:hover': { /* styles */ }
This means the child component inside the parent that is in hover state:
'&:hover .child': { /* styles */ }
You can also omit the ampersand &
if you're using a pseudo-class:
':hover .child': { /* styles */ }
Complete code using sx
prop (The same style object can also be used in styled()
):
<Box
sx={{
width: 300,
height: 300,
backgroundColor: "darkblue",
":hover .child": {
backgroundColor: "orange"
}
}}
>
<Box className="child" sx={{ width: 200, height: 200 }} />
</Box>
Source: stackoverflow.com
Related Query
- How do you change a style of a child when hovering over a parent using MUI styles?
- How to style child when hover on parent using Glamorous
- How to notify parent component of property change when using react hooks?
- How to trigger a state change when hovering over an element
- How to show/hide component in parent component via a button in a child component when using a map of buttons?
- React How to change state value from child to Parent using useState and useContext
- Style Mui child component within parent component using CSS modules
- How do I change state of MUI Data Grid when using a checkbox in cellRender?
- How to get parent props in child component when using styled component in react
- how to prevent child component from reload when the parent state is change
- How do you remove a parent table row when child "delete" button is clicked in React JS?
- How to apply css to parent element when child focused in Mui V5?
- How to change visibility of another class when hovering using jss
- How can I set the state of my parent component from the child component when using react-router?
- When using a functional component, why do parent state changes cause child to re-render even if context value doesn't change
- How do I use react context API to pass data from parent component to child component when using react-router in the parent component in React.js?
- How to hide a child element as default and show it when users over over a parent element with material ui(react.js)?
- How do I pass an object (created by a buttonClick event) from child to parent in react when already using props for a styled button
- How to pass styles from a child to the parent using styled components
- How do you change parent's state from child when the state is a database table?
- how do you single select change the value when the radio button is checked, using react hooks?
- How to change the style of a button when it is clicked in react using css?
- Using React, how do you pass a function from a parent component to a child component and run it in the useEffect hook?
- How to prevent child component from re-rendering when using React hooks and memo?
- How do you call fitBounds() when using leaflet-react?
- How do I change the shape of a button in MUI using theme?
- How to re render parent component when anything changes in Child Component?
- How to enable Ctrl + Z when you change an input text dynamically with React?
- How to change scrollbar when using Tailwind (next.js/react)
- How do I change props from a child component using hooks?
More Query from same tag
- How can I make useEffect react hook rerender based on a variable value?
- Convert A function react component To a react class To Add ref attribute
- What type is best to pass one React Component to another
- Error thrown from child component in componentDidMount lifecycle method is not caught in error boundary
- Form validation React function component with useState
- React Hooks - useEffect, call fuctions just when I update an specific property
- Performance - frequently rendering the same large set of images
- Render method returns null in react router v4
- React send state with history.push
- Why can't functions call each other inside my <App /> component in React
- Cannot import dat.gui in react-three-fiber
- Update component state from Redux store
- Add attribute based on condition from onClick React js
- Importing SASS Bootstrap into React
- Compound Component for Storybook Reactjs
- In React, is it a good practise to return null if props is empty
- React - superagent request per mapped item
- React/Typescript: Selected items counter logic
- fonts are not saved on deploying on vercel next js
- Material UI - why InputBase ref is undefined
- React Uncaught TypeError: Cannot read property 'replace' of undefined
- Optimizing fetching api data with custom React hooks on searching by keyword change
- Simple Javascript animation in Gatsby
- how to hide play button until image loaded in javascript
- How to make a shorter ternary conditional operator in a React functional component?
- How can I store all the dynamic values and attribute labels in a state in react js
- Leaflet: Map container not found
- React Native Navigation override goBack() of header back button in Stack Navigator
- Fetch more content as user is scrolling down
- How do we use two themes on the same DOM element when using a ThemeProvider?