Marek Czyż
Marek Czyż

Reputation: 199

ReactJS onClick event which disable clicking second time on <a> tag

I'm looking a solution how to prevent to clicking and saving second time the same follower through <a> tag.
This is my code:

<a className={this.followClasses(user.following)} 
   onClick={this.followUser.bind(this, user.id)}
   disabled={user.following}>
  <i className="material-icons">person-pin</i>
</a>

onClick runs a function which save to DB a connection between current user and other user that the current user wants to follow second one and change a color from grey to grey. But when I clicked it once there is a possibility to click it twice and this way connection between a users is doubled. As I've checked there is no such attr like disable for <a> so is there any other possible solution to make unable to click it second time?

This is callback function for onClick:

followUser(userId){
  UserActions.followUser(userId);
}

Upvotes: 1

Views: 343

Answers (2)

Marek Czyż
Marek Czyż

Reputation: 199

Ok guys. Ive coped with this problem. I've added following variable to the followUser(userId, following), the same I had used to color <a> tag and it works!

    followUser(userId, following){
    if(!following){
        UserActions.followUser(userId);
    }
}

Upvotes: 0

lupatus
lupatus

Reputation: 4248

You can do it simply like this:

followUser(userId) {
    if (!this.followUserClicked) {
        this.followUserClicked = true;
        UserActions.followUser(userId);
    }
}

although it depends on your structure, might be better to consider storing this value in some higher level object to not loose value on view updates. I would suggest to rather handle that in UserActions than in view.


The problem you can face with your code is that your node is probably not re-rendered after user.following changes, keep user.following value in component's state, track when changes and do this.setState({following: user.following}) after it changes, that will trigger view update.

Upvotes: 1

Related Questions