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!

3
  • What do you mean "an empty tag"? Commented Sep 30, 2020 at 7:02
  • Sometimes the api returns <p></p> like that and it causes the component to render. Commented Sep 30, 2020 at 7: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: stackoverflow.com/questions/494143/…) Commented Sep 30, 2020 at 7:10

1 Answer 1

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>
  )}
Sign up to request clarification or add additional context in comments.

2 Comments

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?
Just flip the boolean. I've updated the code above. !checkForEmptyTags(item.description)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.