Rotate icon when TouchableOpacity onPress is clicked

1.6k Views Asked by At

I am having the hardest time with rotating my FontAwesome Icon when the TouchableOpacity is clicked. I would like to have the FontAwesome pro icon point downwards when it's been clicked and go back to its original state when clicked again.

<TouchableOpacity onPress={this.toggleExpanded}>
  <View style={{ alignItems: "center" }}>
    <Icon iconStyle={{paddingTop:"13%", paddingRight: 50}} name="play-circle" color="#637182" type="light" size={30} />
  </View>
</TouchableOpacity>
2

There are 2 best solutions below

1
On

You can conditionally have a className on the Icon component called rotated and have a CSS rule based on the className.

In your toggleExpanded function, you can set rotated in component state.

toggleExpanded() {
  ... (whatever else happens in here)
  this.setState({iconRotated: !this.state.iconRotated})
}

<TouchableOpacity onPress={this.toggleExpanded}>
  <View style={{ alignItems: "center" }}>
  <Icon
    iconStyle={{paddingTop:"13%", paddingRight: 50}}
    className={this.state.iconRotated ? "icon-rotated" : ""}
    name="play-circle"
    color="#637182"
    type="light"
    size={30}
  />
  </View>
</TouchableOpacity>

In a CSS file, use

.iconRotated
  transform: rotate(90deg);

If you're not using any CSS files, you'll have to conditionally use inline styling.

const rotation = this.state.iconRotated ? 90 : 0
<TouchableOpacity onPress={this.toggleExpanded}>
  <View style={{ alignItems: "center" }}>
  <Icon
    iconStyle={
      {
        paddingTop:"13%",
        paddingRight: 50,
        transform: `${rotate(rotation)}`
      }
    }
    name="play-circle"
    color="#637182"
    type="light"
    size={30}
  />
  </View>
</TouchableOpacity>
0
On

I implemented it this way. Hope it helps someone!

<TouchableOpacity onPress={this.toggleExpanded}>
  <View style={{ alignItems: "center" }}>
    <Icon
      iconStyle={{
        paddingTop:"13%",
        paddingRight: 50,
        transform: [{ rotate: condition-to-rotate-the-icon ? '90deg' : '-90deg' }] // added this
      }}
      name="play-circle"
      color="#637182"
      type="light"
      size={30} />
  </View>
</TouchableOpacity>