Skip to content
Advertisement

React – Shorten string based on width

I have a container with the width: 500px. In this container there are 2 strings, “iiiiiiiiiiiiiii” and “MMMMMMMMMMMMMMM”. You can clearly see that the “M” string is a lot wider than the “i” string, but both fit in the 500px screen. enter image description here

If i make the container smaller, lets say 350px the M string is too wide and i want to remove some ‘M’s so it can fit as so:

enter image description here

In React i have the following data:

var i = 'iiiiiiiiiiiiiii';
var M = 'MMMMMMMMMMMMMMM';
var containerWidth = 500;

Based on what information do I shorten the strings?

I started out with if string.length > containerWidth / 10, but thats not right because string-length != width. I can’t use getElementById and then use .offsetWidth

Advertisement

Answer

You can do that with css only:

.container {
  width: 350px;
  border: 2px solid black;
  padding: 20px;
  white-space: nowrap; 
  overflow: hidden;
  text-overflow: ellipsis;
}
<div class="container">
  IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII<br>
  MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
</div>

Will result in something like this. Run the snippet for a live demo.

---------------------
| IIIIIIIIIIIIIIIIII|
| MMMMMMMMMMMMMMM...|
---------------------
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement