Home > Blockchain >  understanding logical operators and react rendering
understanding logical operators and react rendering

Time:09-27

please help me in understanding this : i am doing a conditional rendering in react-native something like this

{state.sign && (<Image style={{height:200,width:100}} source{{uri:state.sign}})}

it renders with no issue i have this in stacknavigation and when i try to navigate to the root with navigation.popToTop()

this throws an error . However when i change it to

{ state.sign ? (<Image style={{height:200,width:100}} source{{uri:state.sign}}): null}

it works . there is something that i am not understanding. something where "&&" is continuously monitored and "?:" is processed once and dusted?

CodePudding user response:

Probably you forgot to close the tag?

  <Image
        style={styles.tinyLogo}
        source={{
          uri: 'https://reactnative.dev/img/tiny_logo.png',
        }}
      />

CodePudding user response:

For the most part there's not much of a difference between the two, but one use case where it matters is when it's the return value of rendering. React components can render valid JSX, or null to indicate nothing is to be rendered, and booleans are ignored. Returning undefined isn't allowed.

Conditional Rendering

Inline If with Logical && Operator

This is used if you want to conditionally include some JSX with the rest of the rendered JSX.

Example

return (
  <>
    <h1>A Header</h1>
    <div>Some text on the page</div>
    {state.sign && (
      <Image
        style={{height: 200, width: 100}}
        source{{ uri:state.sign }}
      />
    )}
  </>
);

Inline If-Else with Ternary Operator

This is used if you want to conditionally render one JSX or another JSX along with the rest of the rendered JSX.

Example:

return (
  <>
    <h1>A Header</h1>
    <div>Some text on the page</div>
    {state.sign ? (
      <Image
        style={{height: 200, width: 100}}
        source{{ uri:state.sign }}
      />
    ) : (
      <div>There is nothing to see here!</div>
    )}
  </>
);

Preventing Component from rendering

In rare cases you might want a component to hide itself even though it was rendered by another component. To do this return null instead of its render output.

Here's where the difference matters if what you are trying to conditionally render is the return value of a component.

Invalid because it doesn't return null to render nothing:

return state.sign && (
  <Image
    style={{height: 200, width: 100}}
    source{{ uri:state.sign }}
  />
);

Valid:

return state.sign ? (
  <Image
    style={{height: 200, width: 100}}
    source{{ uri:state.sign }}
  />
) : null;
  • Related