Reputation: 1366
I have a material-ui Button with a startIcon where I'd like to hide the button text on smaller screens but continue to show the icon.
The obvious approach is use the useMediaQuery hook to detect the browser size and render a different component.
However, I have to imagine there is an approach through using the CSS api? At first blush, I could not target the text element to hide it as it is wrapped in the same parent element as the icon. The label
field for the Button CSS api includes the icon, so adding a display: 'none' doesn't work as it hides both the text and the sibling icon element.
Is there a standard approach for this with material-ui.
Upvotes: 1
Views: 9968
Reputation: 81026
Below is an example of one way to do this. This uses a <span>
around the text with a separate class (classes.buttonText
) to control hiding it. The rest of the CSS is for centering the icon (margin: 0
) and reducing the size of the button (min-width and padding).
import React from "react";
import Button from "@material-ui/core/Button";
import { makeStyles } from "@material-ui/core/styles";
import DeleteIcon from "@material-ui/icons/Delete";
const useStyles = makeStyles(theme => ({
button: {
margin: theme.spacing(1),
[theme.breakpoints.down("sm")]: {
minWidth: 32,
paddingLeft: 8,
paddingRight: 8,
"& .MuiButton-startIcon": {
margin: 0
}
}
},
buttonText: {
[theme.breakpoints.down("sm")]: {
display: "none"
}
}
}));
export default function IconLabelButtons() {
const classes = useStyles();
return (
<div>
<Button
variant="contained"
color="secondary"
className={classes.button}
startIcon={<DeleteIcon />}
>
<span className={classes.buttonText}>Delete</span>
</Button>
</div>
);
}
Upvotes: 4