DevAS
DevAS

Reputation: 827

How to Change Icon name when pressed in react native vector icon

I'm using react-native-vector-icons

And I want to change the name of an icon at first time the screen load I can see the icon very well but when pressed it doesn't work anymore and I see question mark ?

this.state={
favIcon:"heart-empty"
}
 <Icon name={`ios-${favIcon}`} style={{ backgroundColor: "red" }} size={30} color="#fff" onPress={() => this.setState({ favIcon: "heart" }, alert(favIcon))} />

any Idea to handle name to accept a variable?

and when I log the this.state.FavIcon it's undefined !!

--

nevermind it's work now :D, I'm just editing the name of an icon when setState, and rename the name of the state

now the new Q is when I pressed the icon I change the icon into "ios-heart", now if I want to press again I want to change to "ios-heart-empty"

the idea of function I wanna do is Add to Favorite and Remove from Favorite

Upvotes: 0

Views: 2300

Answers (2)

Muhammad Mehar
Muhammad Mehar

Reputation: 1055

You can do something as follow:

constructor(props) {
   super(props)

   this.state={ 
      providerId: '',
      providerName: '',
      providerService: '',
      fav: false
   } 

   this.ref = firebase.database().ref(`favorites/${firebase.auth().currentUser.uid}`);
}
componentDidMount() {
    this._onFavourite = this.ref.on('child_added', () => {
        this.setState({
            fav: true
        }, alert("Added To Favorite List"))
    })
    this._onUnFavourite = this.ref.on('child_removed', () => {
        this.setState({
            fav: false
        }, alert("Removed from Favorite List"))
    })
}
componentWillUnmount() {
    if (this._onFavourite) {
        this.ref.off('child_added', this._onFavourite);
    }
    if (this._onUnFavourite) {
        this.ref.off('child_removed', this._onUnFavourite);
    }
}
_favOrUnFav = () => {
    if (!this.state.fav){ 
        const { 
            providerId,
            providerName,
            providerService
        } = this.state;

        this.ref.set({
            providerId,
            providerName,
            providerService
        })
    } else ref.set(null)  OR you can use ref.remove()
}
const {
     fav
} = this.state

<Icon 
    name={`ios-heart${fav ? "" : "-empty"}`}
    style={{ backgroundColor: "red" }} 
    size={30} 
    color="#fff" 
    onPress={this._favOrUnFav} 
/>

I hope it help you.

Upvotes: 1

brian
brian

Reputation: 41

onPress is only available on Icon.Button, not Icon. See https://github.com/oblador/react-native-vector-icons#iconbutton-component for more information about Icon.Button.

Upvotes: 0

Related Questions