📅  最后修改于: 2023-12-03 15:17:33.033000             🧑  作者: Mango
Material UI is a popular UI library for React developers. It provides various UI components to create beautiful and responsive web applications. One of the commonly used components is the Icon component. However, aligning the icon with text can be tricky. In this tutorial, we will explore different ways to align icons with text in Material UI using JavaScript.
One of the easiest ways to align icons with text is to use flexbox. Material UI provides a Grid component that uses flexbox. We can use the Grid component to create a row with an icon and text. Here is an example:
import React from 'react';
import Grid from '@material-ui/core/Grid';
import Icon from '@material-ui/core/Icon';
import Typography from '@material-ui/core/Typography';
function IconWithText() {
return (
<Grid container alignItems="center">
<Grid item>
<Icon>star</Icon>
</Grid>
<Grid item>
<Typography>Rating</Typography>
</Grid>
</Grid>
);
}
export default IconWithText;
In the above example, we created a Grid container with two Grid items. The first item contains an Icon component, and the second item contains a Typography component. We used the alignItems property to align the items vertically in the center.
Another way to align icons with text is to use CSS. We can add a CSS class to the Icon component and use CSS to position the icon. Here is an example:
import React from 'react';
import Icon from '@material-ui/core/Icon';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles((theme) => ({
icon: {
marginRight: theme.spacing(1),
verticalAlign: 'middle',
},
}));
function IconWithText() {
const classes = useStyles();
return (
<div>
<Icon className={classes.icon}>star</Icon>
<Typography component="span" variant="body1" display="inline">
Rating
</Typography>
</div>
);
}
export default IconWithText;
In the above example, we created a CSS class using the makeStyles hook. We added a margin-right to the class to create some space between the icon and the text. We also added a vertical-align property to align the icon with the text. We applied this class to the Icon component.
In this tutorial, we explored two different ways to align icons with text in Material UI using JavaScript. We used flexbox and CSS to position the icon. You can use either of these methods, depending on your preference. I hope you found this tutorial helpful!