How to Create Material-UI Chips with Vertical Orientation

Chips are handy components that quickly convey information. From the Material-UI docs: “Chips are compact elements that represent an input, attribute, or action.”

Chips commonly are a circle or a horizontally-shaped oval. However, a unique take on chips is the vertical chip, which we’ll create in this demo.

YouTube version of this article here.

Chip JSX

The JSX can vary depending on what customizations are needed in your Material-UI Chip component.

In this chip, I use avatar and deleteIcon (deleteIcon might not have anything to do with actually deleting).

<Chip
className={classes.root}
variant="outlined"
size="small"
avatar={<Avatar>M</Avatar>}
label={
<div>
Vertical
<br />!
</div>
}
clickable
color="primary"
onDelete={handleDelete}
deleteIcon={<DoneIcon />}
/>

The avatar creates the ‘M’ image at the top of the chip, and the deleteIcon gives us the checkmark at the bottom.

Chip Styling

Most of the unique code for creating the vertical chip is found in the styling:

root: {
display: "flex",
flexDirection: "column",
height: "100%",
"& .MuiAvatar-root": {
margin: "4px 0px"
},
"& .MuiChip-label": {
wordWrap: "break-word",
whiteSpace: "normal",
textOverflow: "clip",
textAlign: "center",
fontSize: 16,
width: 12
},
"& .MuiChip-deleteIcon": {
margin: "8px 0px"
}
}

First, we add flexDirection: column in the chip root. This stacks the child elements vertically. height: “100%” is needed to stretch the outermost div of the chip so that it grows to an appropriate height to show all children.

“& .MuiAvatar-root” targets the “avatar” div generated by Material-UI. All I added was a bit of margin to override the default margin on the avatar. Take a look at the dev tools screenshot below to get an understanding of what that generated code looks like (and how the Material-UI styling API works).

“& .MuiChip-label” required a little more creativity. wordWrap: “break-word”, whiteSpace: “normal”, textOverflow: “clip”, textAlign: “center” were all required in order to get a nice vertical look to for the chip text. For example, by default MUI had textOverflow: “ellipsis”, which needed to be overridden. The wordWrap: “break-word” was required to get word breaks in the middle of the word, even where there wasn’t a space.

Finally, we have “& .MuiChip-deleteIcon” to override default icon margin.

That’s really all there is to it. The most challenging thing may be finding a use case for this nifty component 😆.

Resources:

Expand your JavaScript knowledge with these 50 difficult JavaScript questions!

View Code Sandbox here.

Share this post:

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.