Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a sibling combinator in material ui usestyles

I'm trying to change the background of one div on the hover of another using material ui.

The standard css is:

#a:hover ~ #b {
   background: #ccc;
}

This is my attempt in material ui.

const useStyles = makeStyles(theme => ({
a: {
  background:'#fff',

},
b: {
    background:'#fff'
    '&:hover ~ #a': {
       background:'#eee'
    }
}));
like image 939
James Celestino Avatar asked Dec 13 '19 18:12

James Celestino


People also ask

How does the general sibling Combinator work?

The general sibling combinator (~) separates two selectors and matches the second element only if it follows the first element (though not necessarily immediately), and both are children of the same parent element. Syntax. Example. CSS.

What styles can be applied to material-UI components?

The majority of styles that are applied to Material-UI components are part of the theme styles. In some cases, you need the ability to style individual components without changing the theme.

How do I use makestyles in material-UI?

By calling useStyles () within the component, you have your classes object. Another important thing to point out is that makeStyles is imported from @material-ui/styles, not @material-ui/core/styles. Most Material-UI components have a CSS API that is specific to the component.

Should I use withstyles or makestyles for components?

I highly recommend taking a look. The makeStyles hook is the current (V4) “proper” way to create styles for components. The underlying logic is the same as withStyles according to the docs. There’s one less import needed for makeStyles compared to withStyles (not shown in my code below).


1 Answers

$ is the character to use when referencing another rule name ("b" in this case). You can find this documented here. #b would be the CSS syntax for matching an element with an id of "b".

Below is a working example.

import React from "react";
import ReactDOM from "react-dom";

import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({
  a: {
    "&:hover ~ $b": {
      backgroundColor: "#ccc"
    }
  },
  b: {}
});
function App() {
  const classes = useStyles();
  return (
    <div>
      <div className={classes.a}>This is a</div>
      <div className={classes.b}>This is b</div>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Edit Sibling selector JSS

like image 165
Ryan Cogswell Avatar answered Oct 31 '22 21:10

Ryan Cogswell