Ad

React OnClick Function Only Fires Once Upon Rendering To DOM

- 1 answer

I have the following example of a React component that renders tags to the DOM based on the component's state. The intention is to remove the item from the state's tags array once the delete_tag anchor is clicked. For now, I've just set it to alert the user.

  getInitialState: function () {
    return {
      el: 'times',
      tags: ['dog', 'cat']
    };
  },

  render: function () {
    let that = this;
    return (
      <div id={this.state.el}>
        <div className="center-form">
          <div className="tag_div">
            { this.state.tags.map(function(item) {
                return (
                <div className="tag">
                  {item}
                  <a className="delete_tag" onClick={alert(item)}></a>
                </div>
                );
              })
            }
          </div>
        </div>
      </div>
    );
  }

Using the above code, immediately before every tag is rendered, the user gets alerted. Afterwards, the tags render, but the delete_tag anchor does not respond to any clicks.

I found this odd given that other functions in this component, being used in a similar way with onClick={that.function()} seem to work as intended. Why isn't this onClick attribute behaving as expected?

Ad

Answer

You need to pass onClick a function. The value you passed - alert(item) - is not a function, it's just an invocation of alert.

Instead, you want:

onClick={function () { alert(item); }}

Or if you're using ES6:

onClick={() => alert(item)}
Ad
source: stackoverflow.com
Ad