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:

JavaScript

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:

JavaScript
JavaScript

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

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement