JS/React: How to truncate text with an icon instead of ellipsis?

Viewed 40

How to truncate text with JS/React, and replace the end of the line with a custom SVG icon instead of the CSS default ellipsis (...)?

Example situation:

.container {
  width: 150px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  background: #90e4ff;
  margin-bottom: 8px;
  padding: 2px;
}
<div class="container">
  The text here fits.
</div>

<div class="container">
  This text here is way too long and certainly doesn't fit.
</div>

The output in the second div with the too long text is: This text here is way...

But the desired output would be: This text here is way<CustomIcon>

1 Answers

Thank you for the good question:) By CSS only you cannot use an icon. I tried to think out a solution with JS. As you can see if the background of the SVG is transparent, the text below is visible. So better to use white background to cover the text.

Another important thing is that you need to use spans because divs have default width of 100%.

const containers = document.querySelectorAll('.container');
        
        for (let i=0; i< containers.length; i++) {
           
            if (containers[i].offsetWidth > 150) {
                containers[i].style.width = "150px";
                containers[i].style.setProperty('--height', '20px');
                containers[i].style.setProperty('--width', '20px');
                
            }
        }
.container {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: clip;
    background: #90e4ff;
    position: relative;
    display: inline-block;
}
.container:after {
    content: "";
    width: var(--width, 0);
    height: var(--height, 0);
    background: url("https://www.svgrepo.com/show/5044/heart.svg") 0 0 no-repeat;
    position: absolute;
    top: 0;
    right: 0;
    display: inline-block;
    background-size: contain;
}
<span class="container"> The text here.</span>
<span class="container"> This text here is way too long and certainly doesn't fit.</span> 

Related