search

Home  >  Q&A  >  body text

Functionality without using <br> html to add line breaks

I'm currently learning Vue JS and I made a simple app that pulls information from an API and displays facts about a country based on a given 2 letter country code. Data retrieved from the API maps to country and properties. It stores detailed information about a country such as time zone, currency, population, etc. But some information is missing for some countries. I've been trying to get the UI to display a line break when one of the pieces of information is missing.

Here, if the data obtained is null or an empty array, the items in the country and properties dictionaries are empty strings.

this.country.name = countryName == null ? "" : countryName;
          this.country.capital = capital == null ? "" : capital;
          this.country.currency = currency == null ? "" : currency;
          this.country.phone = phone == null ? "" : phone;
          this.country.emoji = emoji == null ? "" : emoji;
          this.country.languages = languages.length == 0 ? "" : languages;
          this.country.continent = continent == null ? "" : continent;

          this.properties.demonym = demonym == null ? "" : demonym;
          this.properties.area = area == null ? "" : area;
          this.properties.timezones = timezones.length == 0 ? "" : timezones;
          this.properties.population = population == null ? "" : population;

In the method I have a function that returns on the screen if any value of country or
properties
is equal to the empty string Show line breaks.

convertToLineBreak(txt) {
  if (!txt) {
    return txt.replace(txt, "<br>");
  }
  return txt;
}

This is how it appears in the UI, which is not what I want.

This is my app.vue. My main concern is the above, I'm also looking for feedback on how to improve the code. I would be grateful for any feedback. Thank you so much.

P粉567112391P粉567112391473 days ago664

reply all(1)I'll reply

  • P粉659516906

    P粉6595169062023-09-09 00:07:27

    After you get the data from the API, it's a good idea to map it into the correct structure (JavaScript object). Therefore, you can control the blanking of details (properties) or transform the data for other purposes.

    For example:

    "item": {
     "firstItem": "currency",
     "secondItem" : "timeZone"
     ...
    }
    
    
    const item = {currency: item.firstItem, timeZone: item.secondItem, ...}

    reply
    0
  • Cancelreply