Stan Kurilin
Stan Kurilin

Reputation: 15812

Extracting styles from material ui component

AppBar applies some styles for children of specific types. Unfortunately it happens only to direct children

<AppBar title="first" iconElementRight={
    <FlatButton label="first" />
}/>
<AppBar title="second" iconElementRight={
    <div>
        <FlatButton label="second" /> <!-- styles are not applied -->
    </div>
}/>

jsfiddle

Hopefully, it seems like AppBar component exposes getStyles method.

exports.getStyles = getStyles; 

Unfortunately I cannot figure out way to consume it. Is there are any way do it rather than redefining all styles on my own?

PS I'm importing components in with import directive

import AppBar from 'material-ui/AppBar';

Upvotes: 2

Views: 2688

Answers (2)

ryanjduffy
ryanjduffy

Reputation: 5215

Sounds like you need a custom component to reroute the styles to your desired child. This version only forwards style to the child and the rest stay on the wrapping component (a <div> by default) but could be customized to your requirements.

        const StyleDelegate = function (props) {
  const {component: Component, children, style, ...rest} = props;
  // pass style to the only child and everything else to the component
  // could be further customized for other props
  return (
      <Component {...rest}>
          {React.cloneElement(children, {style})}
      </Component>
  );
};

StyleDelegate.defaultProps = {
    component: 'div'
};

const AppBar = function (props) {
  return (
    <div>
      {props.title}
      {React.cloneElement(props.iconElementRight, {style: {color: 'blue'}})}
    </div>
  );
}
  
ReactDOM.render(<AppBar
                  iconElementRight={<StyleDelegate><span>Icon</span></StyleDelegate>}
                  title="title" />,
                document.querySelector('#app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

Upvotes: 1

QoP
QoP

Reputation: 28407

MuiThemeProvider adds a muiTheme object to the context so you can get all the styles from there.

Comp.contextTypes = {
  muiTheme: React.PropTypes.object
}

render: function () {
        let {appBar} = this.context.muiTheme; // appBar styles here
        ...
}

jsfiddle

Upvotes: 1

Related Questions