Angular to React | Logo
 

What’s the Equivalent of an Ng-Click Directive in a React Component?

Hate paperwork but love getting paid? Invoice Like a Boss

To register a click handler with a DOM element inside a React component, just assign the function name to the onClick attribute and enclose it with curly braces. Keep reading for code samples below.

In Angular, you’re probably accustomed to registering a click handler using the ng-click directive. First, you create a function as a property of the $scope object, and then you assign the function name to the ng-click directive in the view template. Here’s an example:

AngularJS Code Sample for ng-click

Start out by defining your click handler function as a property of your $scope object:

.controller('NgClickDemoCtrl', function($scope) {

  $scope.clickCount = 0;

  $scope.handleClick = function() {
    $scope.clickCount++;
  };

});

Then, in your view, you would use the ng-click directive like this:

<a ng-click="handleClick()">
  I`ve been clicked {{clickCount}} time(s)
</a>

React Alternative to ng-click

In React, the process is very similar. If you’re using JSX, you simply create a function and assign its name to the onClick attribute of a DOM element. Here’s an example:

var ClickDemoComponent = React.createClass({
  getInitialState: function() {
    return { clickCount: 0 }
  },
  handleClick: function() {
    this.setState({clickCount: this.state.clickCount+1});
  },
  render: function() {
    return (
      <button onClick={this.handleClick}>
        I`ve been clicked {this.state.clickCount} time(s)
      </button>
    );
  }
});

Keep in mind that React abstracts the actual DOM with a virtual DOM. This virtual DOM has a synthetic event handling system that makes handling click events consistent across varied browsers. So, you’re not actually wiring up the native onclick event handler directly. React’s abstraction allows you to focus on functionality without worrying about the nuances of event systems in different browsers.

If you want to take this a step further, you can build a dynamically repeating navigation menu by combining onClick with Array.map inside your React component. Learn how to use Array.map as the React equivalent to ng-repeat.

Looking for a job? With Hired, companies apply to you, not the other way around. It's free for candidates, plus you get a $1000 hiring bonus! Get started and find your dream job today!
Interested in Writing for Us?

Website developed by Michael Martin  (michael@angulartoreact.com
© 2015-16, All Rights Reserved