rohan
rohan

Reputation: 193

Second layer of conditional statement within inline condition react

I am trying to check the trigger status if it is new, and after that i need to check another condition and based on which i need to display tagone or tagtwo.

I have been trying to find inline documentation for this.

<modalscrolling  onClose={this.props.toggleModal} open={openModal} 
 trigger={isNew ? 
<sometag /> : 
<TagOne  />}>
<TagTwp />}
>

the other approach i am trying is to send it to a different function. Any suggestions to deal with this :)

Upvotes: 1

Views: 65

Answers (4)

Ayyappa Gollu
Ayyappa Gollu

Reputation: 966

you can have nested ternary operators as following,

App.js

import React from "react";
import "./styles.css";
export default function App() {
  var isNew = true;
  var tag = 1;
  return (
    <div className="App">
      {isNew ? (
        tag === 1 ? (
          <span>tag1</span>
        ) : (
          <span>tag2</span>
        )
      ) : (
        <span>notnew</span>
      )}
    </div>
  );
}

demo: https://codesandbox.io/s/ecstatic-shape-r64i8

but i would suggest extract inside teranary operation to another function component which takes "tag" as input. it helps to extend your code easily and make it more readable.

App.js with another after refactoring

import React from "react";
import "./styles.css";

const AnotherCompoent = ({ tag }) => {
  return tag === 1 ? <span>tag1</span> : <span>tag2</span>;
};

export default function App() {
  var isNew = true;
  var tag = 1;
  return (
    <div className="App">
      {isNew ? <AnotherCompoent tag={tag} /> : <span>notnew</span>}
    </div>
  );
}

demo: https://codesandbox.io/s/affectionate-hertz-1ou77

Upvotes: 2

Muhammad Zeeshan
Muhammad Zeeshan

Reputation: 4748

You can do something like this:

<modalscrolling  onClose={this.props.toggleModal} open={openModal} 
 trigger={isNew ? <SomeTag /> : secondLevelCondition ? <TagOne  /> :<TagTwp /> }
/>

Upvotes: 2

Niraj Patel
Niraj Patel

Reputation: 810

trigger= { isNew ? <sometag/> : { anothercond ? <TagOne /> : <TagTwo/> }}.

Is this what you're looking for?

Upvotes: 0

Amit Mendapara
Amit Mendapara

Reputation: 83

Ternary operator is better option as it helps understand the component markup. If the conditional parts are big, convert them to seperate functional components.

Upvotes: 0

Related Questions