TIL – How to truncate a string and make it appear on hover in React/HTML/CSS

There are a few ways to truncate text and make it appear on hover in React. “Truncate” means shortening the text and following it with an ellipsis, like so: “really long text” becomes “really lon…”

React

We can use a little trick. Instead of using the hover psuedo-class of the paragraph element, we can use the title attribute which displays its content in a tooltip.

Note, I’m using the React Styled Components library which allows me to use CSS in React

Here is the styles file


export const Text = styled.p`
color: #a5a9b5;
font-family: Inter;
font-size: 10px;
font-weight: 500;
letter-spacing: 0em;
line-height: 12px;
text-align: right;
cursor: default;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
`;

Here is the React code:

<Text >really really long text</Text>

HTML and CSS

To do this using HTML and CSS, we can add the following styles to our HTML:

<p class="text">
Lorem ipsum lorem ipsum lorem ipsum ipsum lorem ipsum
</p>
.text{
text-overflow: ellipsis; // this line adds the ellipsis
margin-bottom: 12px;
cursor: pointer; // this changes the cursor
word-break: break-all;
overflow:hidden; // this hides the overflowing text
white-space: nowrap;
}
.text:hover{
overflow: visible; // this makes the overflowing text visible on hover
white-space: normal;
height:auto;
}