Wahidullah Shadab
Wahidullah Shadab

Reputation: 790

React <Text> with ternary conditional operator

I am pretty new to react-native and I don't know how to find a solution for what I am trying to achieve. I have multiple functions which either return null or a string. I want to show the return value when it's not null. for example my functions are

//these functions either return null or a string
const a =() => { ...};
const b =() => { ...};
const c =() => { ...};

I have a <Text> component and I want to show the return values from the functions inside my <Text> component.

Right now I am doing it in the following way

<Text>
  {a()}{b()}{c()}
</Text>

Now everything works fine and The text will only show the return value when it is a string.

I want to add a ternary conditional operator and check whether a new variable tmp is undefined or not. if tmp is not undefined the <Text> should show tmp value otherwise It should show the return value of the function that I have above.

<Text>
  {tmp !== undefined ? tmp : }{a()}{b()}{c()}
</Text>

if I do something like

<Text>
  {tmp !== undefined ? tmp : (
  a();
  b();
  c();
  )}
</Text>

and if tmp is undefined it will show the null returned from function too. but I don't want the null returned from functions to be show like the first example.

Upvotes: 1

Views: 2827

Answers (2)

Abraham
Abraham

Reputation: 9875

There are multiple ways to accomplish this, In React Native you can have nested <Text> components. Insted of using a ternary operator, I would do it like this:

<View>
  {tmp && (
    <Text>
      {_a && <Text>{_a}</Text>}
      {_b && <Text>{_b}</Text>}
      {_c && <Text>{_c}</Text>}
    </Text>
  )}
</View>

See the snack https://snack.expo.dev/@abranhe/undefinedvalues

Upvotes: 0

Abe
Abe

Reputation: 5508

Could your a, b, and c functions return an empty string instead of null?

If so, you could rewrite your answer as:

<Text>{tmp || `${a() + b() + c()}`}</Text>

If not, it's a little more cumbersome to write, but the same idea would work:

<Text>{tmp || `${a() || ''}${b() || ''}${c() || ''}`}</Text>

Upvotes: 2

Related Questions