Arrange a series by the actual pixel width of the string

Imagine you have an array of tags represented as strings and you need to display them in a narrow view.

Some tags are smaller, allowing for 2 to fit on one line, while larger tags require their own line.

Your goal is to sort the array so that the smallest tags appear first and try to place multiple tags on the same line whenever possible.

The conventional method of sorting strings by length doesn't seem to be working. Here's an example:


{
item.tags
.sort(({ name }) => name.length)
.map(({ name }, k) =>
<li key={k}>#{name}</li>
)
}

For instance, let's say each letter "i" takes up 5 pixels and "m" takes up 15 pixels. If your line can accommodate 50 pixels, the tags "iiiii," "mmm," and "iiiii" would render like this:

|   iiii    |
|    mmm    |
|   iiii    |

You're looking for a way to accurately calculate the rendered width of each string based on its characters and font type. Additionally, you want to sort the array according to this calculated width for use in a React Component.

The desired output should look like this:

[ 
"iiiii" (25px), 
"iiiii" (25px), 
"mmm" (45px)
]

This sorting will allow you to display the tags as follows:

| iiii iiii |
|     mmm    |

Answer №1

If you want to display the tags in a specific order, you can render them as shown below and then utilize jQuery for sorting.

//To sort the tags using jQuery, you can do it after rendering.

    $('.tag').sort( function(a,b) {
       return $(a).width() - $(b).width();
    }).appendTo('.container');
 <div class="container">
  <i class="tag">iiii <br/></i> <!-- => (25px) -->
  <i class="tag">mmm <br/></i>  <!-- => (45px) -->
  <i class="tag">iiii <br/></i> <!-- => (25px) -->
</div>
<script
  src="http://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>

I included the <br/> in the tags for better visibility.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Design a customizable overlay with a moveable and size-adjustable layer below it

After working with kineticjs, I successfully created an app that allows images to be draggable and resizable, which is great progress; Now, I am facing a challenge: I want to have an overlay in the center with a block of variable height/width that display ...

Is there a JavaScript alternative to wget for downloading files from a specified url?

"wget http://www.example.com/file.doc" can be used to download the file to the local disk. Is there an equivalent way to achieve this in JavaScript? For example, let's look at the following HTML snippet. <html> <head> <script langu ...

Creating a universally accessible handlebars helper in ExpressJS

I have a basic handlebars helper file located in helpers/handlebars.js: var hbs = require('express-handlebars'); hbs.registerHelper("inc", function(value, options) { return parseInt(value) + 1; }); Unfortunately, I am unable to utilize the ...

What is the best way to incorporate the skrollr-body tag without altering the overall height of the

Skrollr has been a game-changer, so thank you to the geniuses behind it. I made sure to properly place the skrollr-body tag around all elements except for the fixed background in order to make it work on mobile. However, I'm noticing that it is cutti ...

Notification window when the page is being loaded

My goal is to have a module or alert box display when my website is opened, and then disappear after 5 minutes. To see an example of what I'm looking for, take a look at this website: On that website, there is a facebook.com box that automatically d ...

Why is it that jQuery is not working in Internet Explorer but works fine in Firefox?

Below is the code for handling file upload onchange event: <input type='file' onchange="displayFilePath(this);" id="loadfile" /> This text field will display the full path of the uploaded file. <script type="text/javascript"> fun ...

Formcontrol is not functioning properly with invalid input

I am attempting to style an input field with a FormControl using the :invalid pseudo-class. Here is my code snippet: scss input:invalid { background-color: red; } html <input type="text" [formControl]="NameCtrl"> Unfortunate ...

Enhancing the functionality of radio buttons through event changes and optimizing related features

I am searching for a more efficient method to reuse functions that serve a similar purpose. For example, I would like to modify various radio buttons that toggle a hide class on different divs. JSFiddle Link How can jQuery be used to create a reusable fu ...

Guide to converting a log string into JSON using Javascript

I encountered a console log that appears as follows: 2021-01-06T09:06:05.541212726Z D saveGarment: Function execution took 736 ms, finished with status code: 204 2021-01-06T09:06:10.844901031Z D saveGarment: Function execution started 2021-01-06T09:06:16.1 ...

extract the field name from the json object

I need to send coordinates to the Google Maps API, but I'm struggling to remove the field name from my JSON object before sending the parameters. Object {TempPoints: "{lat: 51.478,lng: -3.192},{lat: 51.478,lng: -3.192…{lat: 51.47840998047034,lng: - ...

How come my directive is being updated when there are changes in a different instance of the same directive?

For the purpose of enabling Angular binding to work, I developed a straightforward directive wrapper around the HTML file input. Below is the code for my directive: angular.module('myApp').directive('inputFile', InputFileDirective); f ...

jquery's animation causing elements to move abruptly when containing text

For the past hour, I've been grappling with jQuery and could really use some assistance. The following example showcases smooth animations: when you click on either of the divs, the selected div will move left or right if the viewport is wider than 70 ...

Encountered a problem with Vuetify's sass variables

I am currently working on my Vuetify3 project where I need to customize a select dropdown from a library to match the style of Vuetify's select dropdown perfectly. After inspecting Vuetify's select box, I decided to replicate its styles by using ...

What is the best way to shift my content to the next line once it reaches a specific width in my paragraph

When a string is pulled from a database and inserted into a paragraph, it breaks perfectly if the paragraph has spaces. However, if a word is longer than the line, it goes off the page. How can I make it wrap to the next line instead of overflowing off the ...

Upload files using Ajax

Looking to implement Ajax and PHP for file upload functionality. The form includes an <input type="file"> tag, and I aim to enable users to upload a file without having to refresh the page. Any guidance on how to achieve this? While a refresh is no ...

The file or directory does not exist: 'G:Aframara Websiteimages' - ENOENT

Currently, I'm in the process of cleaning up the unused CSS in my website's style.css and bootstrap.min.css files during development. I am utilizing PostCSS and Parcel for this task. After installing PostCSS and Parcel, I proceeded to create a p ...

What is the purpose of the forwardRef function in React?

I've been working on creating a HOC (higher order component) that assists in conditional rendering. Here is the snippet of code I have so far: interface ConditionalProps { renderIf?: boolean } const ConditionalizeComponent = <Props,>( Origi ...

Add a collection of objects to an existing array

const [ posts, setPosts] = useState([]) function addNewPost() { let newPost = [ { id:7, name:'sita', post:'chef' }, { id:8, name:'hari', post:'teacher' } ] ...

The module demoApp could not be instantiated because of an error stating that the module demoApp is not accessible

I am struggling to create a basic Single Page Application (SPA) using Angular and ngRoute/ngView. Unfortunately, I can't seem to get it to work properly. Every time I try, I encounter the error: angular.js:68 Uncaught Error: [$injector:modulerr] Fail ...

Using AngularJs: Invoking Service/Provider in app.config

I need to access my service from within app.config. While searching for a solution, I came across this question, which presented a potential solution that I attempted to implement (not the accepted answer, but the one below with the title "Set up your ser ...