Sometimes, we want to float right or left using the Material-UI app bar.
In this article, we’ll look at how to float right or left using the Material-UI app bar.
How to float right or left using the Material-UI app bar?
To float right or left using the Material-UI app bar, we can set flexGrow
CSS property to 1 to stretch the elements we want to grow in the app bar.
For instance, we write:
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import Typography from "@material-ui/core/Typography";
import Button from "@material-ui/core/Button";
import IconButton from "@material-ui/core/IconButton";
import MenuIcon from "@material-ui/icons/Menu";
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1
},
menuButton: {
marginRight: theme.spacing(2)
},
title: {
flexGrow: 1
}
}));
export default function App() {
const classes = useStyles();
return (
<div className={classes.root}>
<AppBar position="static">
<Toolbar>
<IconButton
edge="start"
className={classes.menuButton}
color="inherit"
>
<MenuIcon />
</IconButton>
<Typography variant="h6" className={classes.title}>
News
</Typography>
<Button color="inherit">Login</Button>
</Toolbar>
</AppBar>
</div>
);
}
We call makeStyles
with a function that returns an object with the root
and title
class properties set to objects with the flexGrow
property set to 1.
Then, we apply the classes.title
class to the Typography
component to stretch the title container to fill all spaces outside the buttons.
As a result, we see the IconButton
stay on the left and the Login button stay on the right of the app bar.
Conclusion
To float right or left using the Material-UI app bar, we can set flexGrow
CSS property to 1 to stretch the elements we want to grow in the app bar.