Popplar
Popplar

Reputation: 279

How to add Material-ui App Bar to class component?

Im trying to add the App Bar from Material-ui (https://material-ui.com/demos/app-bar/) to my NavBar component. Material-ui examples creates a function and exports it.

class App extends Component {
render() {
return (
  <div>
    <NavBar />
  </div>
);
}
}

The NavBar component should return the App Bar from the Material example.

class NavBar extends Component {

render() {
    return (
        //App Bar from material.
    )
}
}

export default NavBar;

So far I have tried to create the const and use it in the navbar component render()

const styles = {
root: {
    flexGrow: 1,
},
grow: {
    flexGrow: 1,
},
menuButton: {
    marginLeft: -12,
    marginRight: 20,
},
};

class NavBar extends Component {

render() {
    return (
        <AppBar position="static">
        <Toolbar>
          <IconButton className={styles.menuButton} color="inherit" aria-label="Menu">
            <MenuIcon />
          </IconButton>
          <Typography variant="h6" color="inherit" className={styles.grow}>
            News
          </Typography>
          <Button color="inherit">Login</Button>
        </Toolbar>
      </AppBar>
    )
}
}

But it doesn't render like the example one, for example the login button position its beside the News label.

Upvotes: 1

Views: 3408

Answers (1)

Tyler
Tyler

Reputation: 2390

Are you wrapping your NavBar component in the withStyles HOC as in the Material example? It looks like you are trying to use the styles object directly in className which will not work as you expect. You have to pass the styles into your NavBar component using withStyles like:

export default withStyles(styles)(NavBar);

Then access the styles in your NavBar from the classes prop:

render() {
  const { classes } = this.props;
  return (
    <AppBar position="static">
      <Toolbar>
        <IconButton className={classes.menuButton} color="inherit" aria-label="Menu">
          <MenuIcon />
        </IconButton>
        <Typography variant="h6" color="inherit" className={classes.grow}>
          News
        </Typography>
        <Button color="inherit">Login</Button>
      </Toolbar>
    </AppBar>
  );
}

The withStyles HOC registers your styles object as CSS and passes the class names into the wrapped component (in this case NavBar) so that you can use them in the render function. You can find more information about withStyles in Material-UI here.

Upvotes: 2

Related Questions