Home > Software engineering >  React <Text> with ternary conditional operator
React <Text> with ternary conditional operator

Time:03-04

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.

CodePudding user response:

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>

CodePudding user response:

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:

const a = () => null;
const b = () => '';
const c = () => 'something';

export default function App() {
  const tmp = true;

  const _a = a();
  const _b = b();
  const _c = c();

  return (
    <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

  • Related