sens_vk
sens_vk

Reputation: 231

React Conditional Rendering to check if something is an empty tag

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!

Upvotes: 0

Views: 433

Answers (1)

Prateek Thapa
Prateek Thapa

Reputation: 4938

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>
  )}

Upvotes: 1

Related Questions