Ad

Material-UI: AppBar => FlatButton Text Unstyled If Not Defined Directly

- 1 answer

Okay, what I want to do is this: I want my AppBar to have a FlatButton with the label "Login". This label should change to "Logout" for obvious reasons.

Now, when I define the AppBar like this then I get the proper styling:

enter image description here

and the code like this:

let App = React.createClass({
    render(){
        return(
            <div>
                <AppBar
                    title="Foobar"
                    iconElementRight={<FlatButton>Login</FlatButton>}
                />
                <div className="LandingPage">
                    {this.props.children}
                </div>
            </div>
        );
    }
});

However, this does not allow me to change the text. Which is why I pulled the FlatButton out into an extra component like this:

let UserName = React.createClass({
    render(){
        return(
            <FlatButton>Login</FlatButton>
        )
    }
});

let App = React.createClass({
    render(){
        return(
            <div>
                <AppBar
                    title="Foobar"
                    iconElementRight={<UserName />}
                />
                <div className="LandingPage">
                    {this.props.children}
                </div>
            </div>
        );
    }
});

What I get as a result is this:

enter image description here

So, what do I have to do differently?

Ad

Answer

Based on the material-ui source code of app-bar.jsx, it checks the display name of the passed component then based on that, applies the needed styles. This code specifically

// app-bar.jsx

if (iconElementRight) {
  switch (iconElementRight.type.displayName) {
    case 'IconMenu':
    case 'IconButton':
      iconElementRight = React.cloneElement(iconElementRight, {
        iconStyle: this.mergeStyles(styles.iconButton.iconStyle, iconElementRight.props.iconStyle),
      });
      break;

    case 'FlatButton':
      iconElementRight = React.cloneElement(iconElementRight, {
        style: this.mergeStyles(styles.flatButton, iconElementRight.props.style),
      });
      break;
  }

// ...

What you have to do is add the FlatButton to your UserName like this

let UserName = React.createClass({
  displayName: 'FlatButton',
  render() {
    return <FlatButton style={this.props.style} >Login</FlatButton>;
  },
});

and lastly, this.props.style is injected to the UserName and you need to pass it on <FlatButton /> to apply the styles.

Ad
source: stackoverflow.com
Ad