saritha
saritha

Reputation: 659

How to use ternary operator for rendering jsx using react?

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.

Upvotes: 1

Views: 102

Answers (3)

Dipesh KC
Dipesh KC

Reputation: 2463

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

Upvotes: 1

Andrea
Andrea

Reputation: 77

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

Upvotes: 0

swapnesh
swapnesh

Reputation: 26732

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

Upvotes: 1

Related Questions