Skip to content

Instantly share code, notes, and snippets.

@rxgx
Last active June 9, 2020 23:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rxgx/b24b43fa8ec436e3d6e3 to your computer and use it in GitHub Desktop.
Save rxgx/b24b43fa8ec436e3d6e3 to your computer and use it in GitHub Desktop.
Render a React Component with Angular Router

For coupling new ReactJS components with legacy angular routing/services.

  • 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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment