0

Need some guidance on ternary operators in react js.

If dataCheck is true, my icon FaSitemap will appear. If it is false, the icon does not appear

However, if it returns an empty response, how do i ensure that the icon does not appear as well? Currently it will appear even if the response is empty even though i return null at the end.

      {
          (dataCheck) ? (
              <span>
                <FaSitemap
                  size="2.5em"
                  color="#1E88E5"
                  cursor="pointer"
                />
              </span>
          ) : (null)
       }
2
  • 1
    What do you exactly mean by returning an empty response? Because technically your ternary operator syntax and logic is correct. Unless the dataCheck object is a string, not a boolean. I am also assuming you have this ternary wrapped in { } Commented Jun 10, 2021 at 12:57
  • [] and {} and ' ' are true even though they empty, want to know more go github.com/denysdovhan/wtfjs Commented Jun 11, 2021 at 3:21

1 Answer 1

1

You can just use logical && which means first it will check for dataCheck, if it is a truthy value then the icon will show else not.

{
  dataCheck && dataCheck.length !== 0 && (
    <span>
      <FaSitemap size="2.5em" color="#1E88E5" cursor="pointer" />
    </span>
  );
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for sharing this good tip! How about if the value returned is [], but seems like it will recognize it as truthy.
@user8779054 In that case, you can check the length of your array. Only show it when it's not 0. For example: {array.length !== 0 && (RENDER YOUR ITEM HERE)}
@user8779054 Answer edited. You just need to add one more condition dataCheck.length !== 0

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.