0

I have the following code:

{item && item.description && (
      <Link
           style={{ display: 'block', paddingBottom: '2px' }}
           title="View Details"
           onClick={() => setIsOpen(!isOpen)}
           {...aria}
            >
           View Details
      <Icon icon={isOpen ? 'collapse_arrow' : 'expand_arrow'}
            marginLeft="5px"
            verticalAlign="bottom"
            />
     </Link>
  )}

The problem is that item.description could be an empty

tag and therefore the condition is met and a Link component is rendered when it actually shouldn't be.

How is the best way I could avoid this case?

Thanks in advance!

sens_vk
  • 171
  • 2
  • 13
  • What do you mean "an empty tag"? – Jayce444 Sep 30 '20 at 07:02
  • Sometimes the api returns

    like that and it causes the component to render.
    – sens_vk Sep 30 '20 at 07:04
  • 1
    Well your 2 options are either do a regex to check for an empty tag, or create an element from the string and checks its inner text (see here for reference: https://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro) – Jayce444 Sep 30 '20 at 07:10

1 Answers1

1

You could use a regex to check for empty tags.

function checkForEmptyTags(tags) {
  if (!tags) return false;

  const EMPTY_TAGS_REGEX = RegExp('<[^>]*>\s*<\/[^>]*>');
  return EMPTY_TAGS_REGEX.test(tags);
}

{item && !checkForEmptyTags(item.description) && (
      <Link
           style={{ display: 'block', paddingBottom: '2px' }}
           title="View Details"
           onClick={() => setIsOpen(!isOpen)}
           {...aria}
            >
           View Details
      <Icon icon={isOpen ? 'collapse_arrow' : 'expand_arrow'}
            marginLeft="5px"
            verticalAlign="bottom"
            />
     </Link>
  )}
Prateek Thapa
  • 4,829
  • 1
  • 9
  • 23
  • I just tried it and it did exactly the opposite - it now renders those who are empty and not those are have tags. How can I change the behaviour? – sens_vk Sep 30 '20 at 07:39
  • Just flip the boolean. I've updated the code above. `!checkForEmptyTags(item.description)` – Prateek Thapa Sep 30 '20 at 12:38