conditional rendering in react code example

Example 1: react style ternary operator

<img 
  src={this.state.photo} 
  alt="" 
  style={ isLoggedIn ? { display:'block'} : {display : 'none'} }  
/>

// or

<img
  src={this.state.photo} 
  alt=""
  style={ { display: isLoggedIn ? 'block' : 'none' } }  
/>

Example 2: if else render react

render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    <div>
      {isLoggedIn ? (
        <LogoutButton onClick={this.handleLogoutClick} />
      ) : (
        <LoginButton onClick={this.handleLoginClick} />
      )}
    </div>
  );
}

Example 3: how to use if else inside jsx in react

renderElement(){
   if(this.state.value == 'news')
      return <Text>data</Text>;
   return null;
}

render() {
    return (   
        <View style={styles.container}>
            { this.renderElement() }
        </View>
    )
}

Example 4: react native conditional rendering

class Component extends React.Component {
	const a = true
	render() {
      return (
    	<Container>
          {a == true
           ? (<Button/>)
           : null
          }
        </Container>    	
	  )
	}
}

This is staying: if a == true, render a button component. 
Otherwise render null, in other words nothing.

Example 5: ternary react

render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    <div>
      The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.    
	</div>
  );
}

Example 6: conditional props react

// single prop
propName={ condition ? something : somethingElse }
propName={ condition && something }
// multiple props
{ ...( condition ? { ...setOfProps } : { ...setOfOtherProps })}
{ ...( condition && { ...setOfProps })}