0

I am trying to create a condition in order to render an error message in a React App. This is my code {channel.length > 0 || sport.length > 0 && ref.current == true && <Error content={"Επιλέξτε φίλτρα"} />}. I am not getting back the Error component even though the conditions are met. Thanks in advance!

3
  • You probably need parentheses somewhere. But in cases like these with complex condition in template, it's better to create a dedicated function in the component with regular and readable if or switch statements. Commented Aug 1, 2023 at 9:39
  • Assigning your logic to a variable, e.g. const showError = a || b && c and then rendering with { showError && <Error />} would generally be a cleaner approach and would avoid the issue you're seeing. Commented Aug 1, 2023 at 9:42
  • if channel.length > 0 is true, then rest of the conditions would not be checked. Better to use the solution suggested in the comment above. Commented Aug 1, 2023 at 9:46

2 Answers 2

1

You must put OR and AND operators in the order of their Precdence. AND (&&) has higher Precedence thatn OR(||). So you may like to put the OR (||) criterion in paranthesis and leave the rest like that. So it should be

{(channel.length > 0 || sport.length > 0) && ref.current == true && <Error content={"Επιλέξτε φίλτρα"} />}

In the above modification, (channel.length > 0 || sport.length > 0) has to be true for the entire block to return true.

You may like to use some alert()to trace the status.

Sign up to request clarification or add additional context in comments.

Comments

1

Use bracker () as && operator has higher presedence than ||

{((channel.length > 0 || sport.length > 0) && (ref.current == true) )&& <Error content={"Επιλέξτε φίλτρα"} />}

Comments

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.