1

i want to render jsx based on condition using react.

if condition1 and condition2 should display button add. if condition1 and !condition2 should display button click me

below is my code,

render = () => {
    return (
        {condition1 && condition2 && (
            <button>add</button>
        )}
        {condition1 && !condition2 && (
            <button>click me </button>
        )}
    );
}

how can i rewrite above code using ternary operator. could someone help me fix this. thanks.

1
  • 3
    Doing this is cleaner then having to nest ternary operators. Commented Jun 5, 2020 at 14:12

3 Answers 3

1

You can write something like this -

{condition1 ? 
  (condition2 ? 
    (<button>add</button>) : (<button>click me </button>) 
  ) : null}

Note - Sometimes ES Linter throws warning for using nested ternary operators in JSX render method. So keep this in mind.

No Nested Ternary

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

Comments

1
condition1 && condition2 ? <button>add</button> : <button>click me </button>;

Comments

0
return ((condition1 && condition2)?(<button>add</button>):((condition1 && !condition2)?(<button>click me </button>):()));

1 Comment

While this code may resolve the OP's issue, it is best to include an explanation as to how your code addresses the OP's issue. In this way, future visitors can learn from your post, and apply it to their own code. SO is not a coding service, but a resource for knowledge. Also, high quality, complete answers are more likely to be upvoted. These features, along with the requirement that all posts are self-contained, are some of the strengths of SO as a platform, that differentiates it from forums. You can edit to add additional info &/or to supplement your explanations with source documentation.

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.