- Create a function that returns the angular route object. This object contains a controller that handles the mounting and unmounting of the React component, as well as a container template to render the component inside of. Note: the
containerId
is arbitrary and only exists to identify the container the component will be placed in.
var registerRouteForComponent = function (componentClass) {
var containerId = 'reactComponentRender';
var controller = function ($scope, $injector) {
if (componentClass) {
var container = document.getElementById(containerId);
var component = React.createElement(componentClass, { '$injector' : $injector });
// Mount Component
React.render(component, container);
// Unmount Component
$scope.$on('$destroy', function () {
React.unmountComponentAtNode(container);
});
}
};
controller.$inject = ['$scope', '$injector'];
return {
'template': '<div id="' + containerId + '"></div>',
'controller': controller
};
};
- Hook it into your angular $routeProvider by passing in the component class. (Not an instance of the component)
var someComponent = require('./components/someComponent');
angular.module('exampleApp', ['ngRoute']).
config(['$routeProvider', function($routeProvider) {
// This is a new react component
$routeProvider.when('/reactComponent', registerRouteForComponent(someComponent));
// This is a legacy angular page
$routeProvider.when('/angularController', {templateUrl: 'template.html'});
}]);
- Access the angular $injector from within your react component for using your registered angular services.
var someComponent = React.createClass({
makeRequest: function () {
var $http = this.props.$injector.get('$http');
$http({method: 'GET', url: '/someUrl'});
},
render: function () {
return React.DOM.button({onClick: this.makeRequest}, 'Make Request');
}
});
module.exports = someComponent;
And that's it!