Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS shows alert message when link is clicked

Tags:

reactjs

The following code shows the alert message as the rules are being bound in the map() function. I do not want this to happen. Instead, how can I bind the onClick() to each link so when the user clicks the link the message then will show? I think it has to do with placing bind(this) somewhere in the map() code but cannot figure it out. Thanks for any help!

const RuleResults = React.createClass({
  showMessage: function (rule) {
    if (rule.ShowMessageToUser == true) {
      alert(rule.MessageToUser);
    }
  },
  render: function () {

    var rules = this.props.businessRules.map((rule) => {
      return (
        <tr>
          <td>
            <a href={rule.HREF} onClick={this.showMessage(rule)} target='_blank'>{rule.Name}</a>
          </td>
        </tr>
      );
    });
    return (
      <div>
        <table>
          <thead>
            <tr>
              <th>Name</th>
            </tr>
          </thead>
          <tbody>
            {rules}
          </tbody>
        </table>
      </div>
    );
  }
});
like image 216
Frekster Avatar asked May 12 '16 15:05

Frekster


1 Answers

You should pass to onClick reference to function instead of call it. To do it you can use .bind or arrow function

  1. <a href={rule.HREF} onClick={ this.showMessage.bind(this, rule) }>..</a>
  2. <a href={rule.HREF} onClick={ () => this.showMessage(rule) }>..</a>

Example

like image 71
Oleksandr T. Avatar answered Oct 10 '22 11:10

Oleksandr T.