Marian Rick
Marian Rick

Reputation: 3440

How to call var in return ()

I can create an output using return () two display two const containing numbers as values:

return (
   <div>
     <span>{const_one}</span> {const_two}
   </div>
)

If a random boolean var statement = true I want to output

return (
   <div>
     {const_one}
   </div>
)

Whenever I use if () functions inside my return () I get an error. How can I achieve this? I have tried to create a const checking the state and create another const that includes the output:

const statement = false;
// or
const statement = true;

let customOutput = '<span>{const_one}</span> {const_two}';

if (statement === true) customOutput = const_one;

return (
  <div>
    {customOutput}
  </div>
)

In this example the const_one or const_two tags are displayed as html text, instead of displaying their values (which are actually numbers):

<span>{const_one}</span> {const_two} instead of <span>24</span> 36.

How can I change the markup to display the const values inside of {customOutput}

Upvotes: 0

Views: 57

Answers (1)

amann
amann

Reputation: 5902

You can use the ternary operator for this:

return (
  <div>
    {statement
      ? const_one
      : <span><span>{const_one}</span> {const_two}</span>}
  </div>
);

Upvotes: 2

Related Questions