React has emerged as a popular library for creating complicated user interfaces, most notably Facebook and Instagram. React is great for building reusable components and one of its strengths is how easily it integrates with other frameworks. In this post I will demonstrate how to integrate a simple React component in an existing Angular application.
As always the best approach for integrating other frameworks with Angular is through a directive. The code below shows how to create a directive that wraps a simple React greeting component.
angular.module('app').directive('greeting',[function(){
return {
restrict:'AE',
scope:{name:'@'},
link: function (scope, elem, attrs){
var GreetingSection = React.createClass({displayName: 'Greeting',
render: function() {
var message = "Good morning " + this.props.data.name + ", how are you?";
return React.createElement('div', {className: "greeting"},message);
}
});
React.renderComponent(GreetingSection({data:scope}), elem[0]);
}
};
}]);
As you can tell from the usage of the directive we are able to pass in information from Angular to the React component and dynamically create the greeting:
“Good morning Joe, how are you?”
<greeting name="Joe"></greeting>