Home > Enterprise >  How do i render ternary operator(if condition) in jsx
How do i render ternary operator(if condition) in jsx

Time:10-05

This here is the question

Make a component called Gate that accepts 1 prop called "isOpen". When isOpen is true, make the component render "open", and when isOpen is false, make it render "closed". Hint: you can do conditional logic inside JSX with the ternary (question mark, ?) operator, inside single braces, like this: {speed > 80 ? "danger!" : "probably fine"} (which evaluates to "danger!" if speed is over 80, and "probably fine" otherwise).

while this is the code :

import ReactDOM from 'react-dom';

const Gate=({isOpen})=> (
  <div>
   { isOpen }
  </div>
)

ReactDOM.render(<Gate {isOpen?<h1>hello</h1>:<h1>not hello</h1>} />, document.querySelector('#root'));```

CodePudding user response:

The isOpen value is in the Gate component, so the condition would go in the rendering within that component:

const Gate=({isOpen})=> (
  <div>
    { isOpen ? <h1>hello</h1> : <h1>not hello</h1> }
  </div>
)

Then when using the component you would pass a value for that prop:

<Gate isOpen={true} />

You can otherwise pass the element to display and put the condition outside the component. For example, taking your original Gate component:

const Gate=({isOpen})=> (
  <div>
    { isOpen }
  </div>
)

In this case the component isn't expecting a condition as a prop, it's expecting something to render. You can conditionally pass it something to render. But you would need that condition available where you use it. For example, the structure would be like this:

<Gate isOpen={true ? <h1>hello</h1> : <h1>not hello</h1>} />

Clearly this is always true, but in this structure you'd simply replace true with whatever your dynamic condition is.

In either case, isOpen is a prop being passed to the Gate component.

CodePudding user response:

All you have to do is using ternary operator in Gate compoent render open or closed as per the value of isOpen as:

CODESANDBOX LINK

const Gate = ({ isOpen }) => <div>{isOpen ? "open" : "closed"}</div>;

If you want to render in H1 then you can do as:

const Gate2 = ({ isOpen }) => {
  return (
    <div>
      <h1>{isOpen ? "open" : "closed"}</h1>
    </div>
  );
};
  • Related