1

I can't figure out how to do the simplest thing in CSS using makeStyles from material-ui.

Imagine this super simple example:

<div classNames={clsx(wrapper, post.new && classes.new)}>
  <p classNames={text}>Post</p>
  <p> Something else </p>
</div>

The styles are really easy as well:

const useStyles = makeStyles({
  wrapper: {
    // styles
  },
  text: {
    // styles
  },
  new: { 
    text: { 
      color: 'red', // this does not work, why? :[
    } 
  }
});

You can probably guess by now what the problem here is. I want wrapper to have new class sometimes and when it happens text gets red. That's it. I have absolutely no clue how to do this.

I know there's '& .something' but this looks like a bad approach and I don't even know exact class name for text because classes are gibberish ( makeStyles-text-somerandomnumber). I don't want to add .new class to everything that needs extra styles, what if I there are multiple paragraphs that need different styles? Impossible to maintain. I guess I must be missing something, it's so trivial, yet, no idea how to do this!

Any help would be highly appreciated!

Wordpressor
  • 7,173
  • 23
  • 69
  • 108

1 Answers1

0
className={`wrapper ${this.state.something}`}

I see that your post is tagged with reactjs, if you are using React you can just dynamically apply the classes by whatever their state is.

Don't forget the backticks for template literals.

Travis
  • 207
  • 1
  • 11
  • 1
    This is a good advice, but won't work in my case, I don't want to add extra class to "text" element. What if I had 150 paragraphs that need to be red? I'd have to add the class to every single one of them. – Wordpressor Mar 18 '21 at 12:37
  • So make a paragraph component that has it's own state and then render each paragraph with the content you want as props that is passed into the element? You could even make a prop that toggles the element state to be new or not. – Travis Mar 18 '21 at 12:43