Skip to content

Image does not render correctly when included in ternary operator #884

@mrblueblue

Description

@mrblueblue
tl;dr

A React Image component did not render correctly when included inside a ternary operator. To get around this, I had to separate the Image as a standalone component. After creating this separate component and requiring it in the original component, the Image rendered correctly according to the logic of the ternary.

Is this the correct behavior for the Image component?

Considering that the separate component and the original Image are functionally the same, I don't see how creating the Image as a separate component would cause this change in behavior.

Background

I wanted to create a 'like' button--its default 'unliked' state being a grey heart and its 'liked' state being a color-filled heart.

To implement this I used a ternary operator in render function's return block.

render: function() {
  return(
    <View style={{flex:1}}>
      <TouchableOpacity onPress={this.props.updateHearts}>
        { this.props.hasPressedHeart ?
         <Image
            source={FullHeart}
            style={{width:30, height:30}}
          />
          :
          <Image
            source={EmptyHeart}
            style={{width:30, height:30}}
          />
        }
      </TouchableOpacity>
    </View>
  );
}

In effect, if the user had already pressed the heart, the image would be a "FullHeart," and if not, then the image would be an "EmptyHeart."

The Issue

The correct image would not render after new props were passed to the component.

I verified that the correct props were correct my rendering the logic of the ternary as text, like so:

<Text>
  {this.props.hasPressedHeart ? 1 : 0}
</Text>

Even when the ternary evaluated to false and displayed "0", the corresponding ternary for the image did not evaluate to "FullHeart".

The Workaround

To get around this problem, I created the heart images as separate components and required them like so:

<View style={{flex:1}}>
  <TouchableOpacity onPress={this.props.updateHearts}>
    <View>
      { this.props.hasPressedHeart ?<FullHeart/> : <EmptyHeart/> }
    </View>
  </TouchableOpacity>
</View>
var FullHeart = React.createClass({
  render(){
    return(
      <Image
        source={{uri: 'http://i.imgur.com/SXHb8nG.png?1'}}
        style={{width:30, height:30}}
      />
    );
  }
})

After doing this, the correct image was rendered after receiving new props.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions