Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue using multiple styles with Material-ui and Radium

I am trying to combine Radium and Material-ui. When I try to apply multiple styles on a single Material-ui component, no style is applied. So, for example, something like this produces no styling applied:

<MenuItem style={[styles.styleOne, styles.styleTwo]} >

Of course, if I do something like:

<MenuItem style={Object.assign({}, styles.styleOne, styles.styleTwo)} >

it works. Is there some way around it or this is the only way to use Radium for combining styles for a Material-ui component? And just to mention, Radium is properly set up, because applying array of styles on, for example, DIV element or works properly. Also, I am open to any suggestion about styling a React project that uses Material-ui library. Thanks!

like image 632
Nenad Rakić Avatar asked Jun 15 '16 07:06

Nenad Rakić


2 Answers

For material-ui components in react, we add styles using the className. If i have to add multiple styles in a material component then below are the methods:

Example 1:

<div className={`${style1} ${style2}`}>

Example 2:

import classNames from 'classnames';
<div className={classNames(classes.style1, classes.style2)} />

Specifically for your case (Radium): What it's doing is merging 2 objects (style1 and style2) into a new anonymous object {} which is what you need to do.

You'll want to be careful when doing this however as you'll need to consider how you merge if both objects define the same key e.g. if style1 and style2 both define a height which do you use?

There's a long list of possible ways to do this on this stackoverflow thread http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically depending on the libraries you're using and your use case they each have their own pros and cons.

like image 83
sidverma Avatar answered Nov 05 '22 00:11

sidverma


Instead of adding classnames, you can also use the clsx module that comes with Material UI and combine your style classes.

{/* using arrays */}
<MyComponent classes={clsx([classes.text, classes.title])} />
{/* using conditions */}
<div className={clsx(classes.root, {
  [classes.base]: true,
  [classes.closed]: !open,
  [classes.open]: open
})]>
  {props.children}
</div>

The Material UI Mini Variant Drawer example does a great job showing this module off.

like image 1
DBrown Avatar answered Nov 05 '22 01:11

DBrown