Convert Figma logo to code with AI

ngReact logongReact

Use React Components in Angular

2,602
261
2,602
0

Top Related Projects

233,534

The library for web and native user interfaces.

97,258

Deliver web apps with confidence 🚀

208,514

This is the repo for Vue 2. For Vue 3, go to https://github.com/vuejs/core

81,903

web development for the rest of us

37,267

⚛️ Fast 3kB React alternative with the same modern API. Components & Virtual DOM.

16,109

:fire: An extremely fast, React-like JavaScript library for building modern user interfaces

Quick Overview

ngReact is a library that allows you to use React components within Angular applications. It provides a bridge between Angular and React, enabling developers to leverage the strengths of both frameworks in a single project. This can be particularly useful when migrating from Angular to React or when integrating React components into existing Angular applications.

Pros

  • Allows gradual migration from Angular to React
  • Enables the use of React's component-based architecture within Angular apps
  • Provides a way to leverage the extensive React ecosystem in Angular projects
  • Facilitates code reuse between Angular and React codebases

Cons

  • Adds complexity to the project structure and build process
  • May lead to performance overhead due to running two frameworks simultaneously
  • Requires developers to be familiar with both Angular and React
  • Maintenance can be challenging as it depends on both Angular and React ecosystems

Code Examples

  1. Using a React component in an Angular template:
<react-component name="MyReactComponent" props="ctrl.componentProps" />
  1. Wrapping a React component for use in Angular:
import { react2angular } from 'react2angular';
import MyReactComponent from './MyReactComponent';

angular.module('myApp').component(
  'myReactComponent',
  react2angular(MyReactComponent, ['prop1', 'prop2'])
);
  1. Using Angular services in a React component:
import React from 'react';
import { useAngular } from 'use-angular';

const MyReactComponent = () => {
  const { $http } = useAngular();

  // Use $http service here
  // ...

  return <div>My React Component</div>;
};

export default MyReactComponent;

Getting Started

  1. Install ngReact:

    npm install --save ngreact react react-dom
    
  2. Add ngReact to your Angular module:

    import 'ngreact';
    
    angular.module('myApp', ['react']);
    
  3. Use React components in your Angular templates:

    <react-component name="MyReactComponent" props="ctrl.componentProps" />
    
  4. Wrap your React components for use in Angular:

    import { react2angular } from 'react2angular';
    import MyReactComponent from './MyReactComponent';
    
    angular.module('myApp').component(
      'myReactComponent',
      react2angular(MyReactComponent, ['prop1', 'prop2'])
    );
    

Competitor Comparisons

233,534

The library for web and native user interfaces.

Pros of React

  • Larger community and ecosystem, with more resources and third-party libraries
  • Better performance for complex applications due to virtual DOM
  • More flexible and can be used for both web and mobile development (React Native)

Cons of React

  • Steeper learning curve, especially for developers new to component-based architecture
  • Requires additional tools and libraries for full-featured applications (e.g., routing, state management)
  • More frequent updates and changes, which can lead to compatibility issues

Code Comparison

React:

import React from 'react';

function MyComponent() {
  return <div>Hello, React!</div>;
}

ngReact:

angular.module('myApp', ['react'])
  .value('HelloComponent', React.createClass({
    render: function() {
      return <div>Hello, ngReact!</div>;
    }
  }));

Summary

React is a more versatile and widely-adopted library with better performance for complex applications. However, it has a steeper learning curve and requires additional tools for full functionality. ngReact, on the other hand, provides a bridge between Angular and React, allowing developers to use React components within Angular applications. This can be beneficial for teams transitioning from Angular to React or those looking to leverage React's component model within existing Angular projects.

97,258

Deliver web apps with confidence 🚀

Pros of Angular

  • Full-featured framework with built-in tools for routing, forms, and HTTP requests
  • Powerful dependency injection system for better modularity and testability
  • TypeScript support out of the box, providing strong typing and improved tooling

Cons of Angular

  • Steeper learning curve due to its comprehensive nature and unique concepts
  • Larger bundle size compared to more lightweight solutions
  • More opinionated, which may limit flexibility in certain scenarios

Code Comparison

Angular:

@Component({
  selector: 'app-root',
  template: '<h1>{{title}}</h1>'
})
export class AppComponent {
  title = 'Hello, Angular!';
}

ngReact:

angular.module('myApp', ['react'])
  .value('HelloComponent', React.createClass({
    render: function() {
      return <h1>Hello, {this.props.name}!</h1>;
    }
  }))
  .controller('MyCtrl', function($scope) {
    $scope.name = 'World';
  });

Summary

Angular is a comprehensive framework offering a complete solution for building web applications, while ngReact is a lightweight library for integrating React components into AngularJS applications. Angular provides more built-in features and better TypeScript support, but comes with a steeper learning curve and larger bundle size. ngReact offers a simpler approach for gradually adopting React in existing AngularJS projects, but lacks the full feature set of a modern framework like Angular.

208,514

This is the repo for Vue 2. For Vue 3, go to https://github.com/vuejs/core

Pros of Vue

  • More comprehensive framework with built-in state management and routing
  • Easier learning curve and simpler syntax
  • Better performance for large-scale applications

Cons of Vue

  • Smaller ecosystem compared to React
  • Less flexibility for custom implementations
  • Fewer job opportunities in some markets

Code Comparison

Vue component:

<template>
  <div>{{ message }}</div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello Vue!'
    }
  }
}
</script>

ngReact component:

import React from 'react';
import {reactDirective} from 'ngreact';

const HelloMessage = ({message}) => <div>{message}</div>;

angular.module('myApp', ['react'])
  .directive('helloMessage', reactDirective(HelloMessage));

Vue offers a more straightforward and concise syntax, while ngReact requires more setup and integration between Angular and React. Vue's single-file component structure combines template, script, and style in one file, making it easier to manage. ngReact, on the other hand, allows for gradual migration from Angular to React, which can be beneficial for large existing Angular projects.

81,903

web development for the rest of us

Pros of Svelte

  • Smaller bundle size and better performance due to compile-time optimization
  • Simpler, more intuitive syntax with less boilerplate code
  • Built-in state management and reactivity without additional libraries

Cons of Svelte

  • Smaller ecosystem and community compared to React-based solutions
  • Less mature tooling and third-party library support
  • Potential learning curve for developers familiar with React or Angular

Code Comparison

Svelte component:

<script>
  let count = 0;
  const increment = () => count += 1;
</script>

<button on:click={increment}>
  Clicks: {count}
</button>

ngReact component:

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  const increment = () => setCount(count + 1);

  return (
    <button onClick={increment}>
      Clicks: {count}
    </button>
  );
}

Summary

Svelte offers a more streamlined development experience with better performance, while ngReact provides the flexibility of combining React components within Angular applications. Svelte's simplicity and compile-time optimizations make it attractive for new projects, but ngReact may be preferred for existing Angular codebases that want to incorporate React components gradually.

37,267

⚛️ Fast 3kB React alternative with the same modern API. Components & Virtual DOM.

Pros of Preact

  • Significantly smaller bundle size (3KB vs. Angular's larger footprint)
  • Faster performance due to lightweight Virtual DOM implementation
  • Easier learning curve for developers familiar with React

Cons of Preact

  • Smaller ecosystem and community compared to Angular
  • Fewer built-in features, requiring additional libraries for complex applications
  • Limited TypeScript support compared to Angular's robust typing system

Code Comparison

ngReact:

angular.module('myApp', ['react'])
  .directive('helloComponent', function(reactDirective) {
    return reactDirective(HelloComponent);
  });

Preact:

import { h, render } from 'preact';

function HelloComponent(props) {
  return <h1>Hello, {props.name}!</h1>;
}

render(<HelloComponent name="World" />, document.body);

Summary

Preact is a lightweight alternative to React, offering a smaller bundle size and improved performance. It's ideal for projects where size and speed are crucial. However, it may lack some features and community support compared to larger frameworks like Angular.

ngReact, on the other hand, allows integration of React components into Angular applications, providing a bridge between the two frameworks. It's useful for gradually migrating from Angular to React or for using React components within existing Angular projects.

The choice between Preact and ngReact depends on project requirements, existing codebase, and team expertise. Preact is better for new, performance-focused projects, while ngReact is suitable for Angular applications looking to incorporate React components.

16,109

:fire: An extremely fast, React-like JavaScript library for building modern user interfaces

Pros of Inferno

  • Significantly faster performance due to its lightweight and optimized virtual DOM implementation
  • Smaller bundle size, leading to quicker load times and reduced network usage
  • More flexible and easier to integrate with existing projects, not tied to a specific framework

Cons of Inferno

  • Smaller community and ecosystem compared to React-based solutions
  • Less extensive documentation and learning resources available
  • Fewer third-party libraries and components specifically designed for Inferno

Code Comparison

ngReact:

angular.module('myApp', ['react'])
  .value('HelloComponent', React.createClass({
    render: function() {
      return <div>Hello {this.props.name}</div>;
    }
  }));

Inferno:

import { render } from 'inferno';

function HelloComponent({ name }) {
  return <div>Hello {name}</div>;
}

render(<HelloComponent name="World" />, document.getElementById('app'));

The code comparison shows that Inferno's syntax is more similar to modern React, while ngReact uses an older React syntax within an Angular module. Inferno's approach is more straightforward and doesn't require integration with Angular, making it potentially easier to use for developers familiar with React-like libraries.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Build Status Pair on this

Note: For a more modern alternative to ngReact, we recommend react2angular, angular2react, and ngimport.

ngReact

The React.js library can be used as a view component in web applications. ngReact is an Angular module that allows React Components to be used in AngularJS applications.

Motivation for this could be any of the following:

  • You need greater performance than Angular can offer (two way data binding, Object.observe, too many scope watchers on the page) and React is typically more performant due to the Virtual DOM and other optimizations it can make

  • React offers an easier way to think about the state of your UI; instead of data flowing both ways between controller and view as in two way data binding, React typically eschews this for a more unidirectional/reactive paradigm

  • Someone in the React community released a component that you would like to try out

  • You're already deep into an Angular application and can't move away, but would like to experiment with React

Installation

Install via Bower:

bower install ngReact

or via npm:

npm install ngreact

Usage

Then, just make sure Angular, React, and ngReact are on the page,

<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/react/react.js"></script>
<script src="bower_components/react/react-dom.js"></script>
<script src="bower_components/ngReact/ngReact.min.js"></script>

and include the 'react' Angular module as a dependency for your new app

<script>
    angular.module('app', ['react']);
</script>

and you're good to go.

Features

Specifically, ngReact is composed of:

  • react-component, an Angular directive that delegates off to a React Component
  • reactDirective, a service for converting React components into the react-component Angular directive

ngReact can be used in existing angular applications, to replace entire or partial views with react components.

The react-component directive

The react-component directive is a generic wrapper for embedding your React components.

With an Angular app and controller declaration like this:

angular
  .module('app', ['react'])
  .controller('helloController', function($scope) {
    $scope.person = { fname: 'Clark', lname: 'Kent' };
  });

And a React Component like this

var HelloComponent = React.createClass({
  propTypes: {
    fname: React.PropTypes.string.isRequired,
    lname: React.PropTypes.string.isRequired
  },
  render: function() {
    return (
      <span>
        Hello {this.props.fname} {this.props.lname}
      </span>
    );
  }
});
app.value('HelloComponent', HelloComponent);

The component can be used in an Angular view using the react-component directive like so:

<body ng-app="app">
  <div ng-controller="helloController">
    <react-component name="HelloComponent" props="person" watch-depth="reference"/>
  </div>
</body>

Here:

  • name attribute checks for an Angular injectable of that name and falls back to a globally exposed variable of the same name
  • props attribute indicates what scope properties should be exposed to the React component
  • watch-depth attribute indicates what watch strategy to use to detect changes on scope properties. The possible values for react-component are reference, collection and value (default)

The reactDirective service

The reactDirective factory, in contrast to the reactComponent directive, is meant to create specific directives corresponding to React components. In the background, this actually creates and sets up directives specifically bound to the specified React component.

If, for example, you wanted to use the same React component in multiple places, you'd have to specify <react-component name="yourComponent" props="props"></react-component> repeatedly, but if you used reactDirective factory, you could create a <your-component></your-component> directive and simply use that everywhere.

The service takes the React component as the argument.

app.directive('helloComponent', function(reactDirective) {
  return reactDirective(HelloComponent);
});

Alternatively you can provide the name of the component

app.directive('helloComponent', function(reactDirective) {
  return reactDirective('HelloComponent');
});

This creates a directive that can be used like this:

<body ng-app="app">
  <div ng-controller="helloController">
    <hello-component fname="person.fname" lname="person.lname" watch-depth="reference"></hello-component>
  </div>
</body>

The reactDirective service will read the React component propTypes and watch attributes with these names. If your react component doesn't have propTypes defined you can pass in an array of attribute names to watch. If you don't pass any array of attribute names, fall back to use directive attributes as a last resort. By default, attributes will be watched by value however you can also choose to watch by reference or collection by supplying the watch-depth attribute. Possible values are reference, collection and value (default).

app.directive('hello', function(reactDirective) {
  return reactDirective(HelloComponent, ['fname', 'lname']);
});

You may also customize the watch depth per prop/attribute by wrapping the name and an options object in an array inside the props array:

app.directive('hello', function(reactDirective) {
  return reactDirective(HelloComponent, [
    'person', // takes on the watch-depth of the entire directive
    ['place', { watchDepth: 'reference' }],
    ['things', { watchDepth: 'collection' }],
    ['ideas', { watchDepth: 'value' }]
  ]);
});

By default, ngReact will wrap any functions you pass as in scope.$apply. You may want to override this behavior, for instance, if you are passing a React component as a prop. You can achieve this by explicitly adding a wrapApply: false in the prop config:

app.directive('hello', function(reactDirective) {
  return reactDirective(HelloComponent, [
    'person',
    ['place', { watchDepth: 'reference' }],
    ['func', { watchDepth: 'reference', wrapApply: false }]
  ]);
});

If you want to change the configuration of the directive created the reactDirective service, e.g. change restrict: 'E' to restrict: 'C', you can do so by passing in an object literal with the desired configuration.

app.directive('hello', function(reactDirective) {
  return reactDirective(HelloComponent, undefined, { restrict: 'C' });
});

Minification

A lot of automatic annotation libraries including ng-annotate skip implicit annotations of directives. Because of that you might get the following error when using directive in minified code:

Unknown provider: eProvider <- e <- helloDirective

To fix it add explicit annotation of dependency

var helloDirective = function(reactDirective) {
  return reactDirective('HelloComponent');
};
helloDirective.$inject = ['reactDirective'];
app.directive('hello', helloDirective);

Reusing Angular Injectables

In an existing Angular application, you'll often have existing services or filters that you wish to access from your React component. These can be retrieved using Angular's dependency injection. The React component will still be render-able as aforementioned, using the react-component directive.

It's also possible to pass Angular injectables and other variables as fourth parameter straight to the reactDirective, which will then attach them to the props

app.directive('helloComponent', function(reactDirective, $ngRedux) {
  return reactDirective(HelloComponent, undefined, {}, { store: $ngRedux });
});

Be aware that you can not inject Angular directives into JSX.

app.filter('hero', function() {
  return function(person) {
    if (person.fname === 'Clark' && person.lname === 'Kent') {
      return 'Superman';
    }
    return person.fname + ' ' + person.lname;
  };
});

/** @jsx React.DOM */
app.factory('HelloComponent', function($filter) {
  return React.createClass({
    propTypes: {
      person: React.PropTypes.object.isRequired
    },
    render: function() {
      return <span>Hello $filter('hero')(this.props.person)</span>;
    }
  });
});
<body ng-app="app">
  <div ng-controller="helloController">
    <react-component name="HelloComponent" props="person" />
  </div>
</body>

Jsx Transformation in the browser

During testing you may want to run the JSXTransformer in the browser. For this to work with angular you need to make sure that the jsx code has been transformed before the angular application is bootstrapped. To do so you can manually bootstrap the angular application. For a working example see the jsx-transformer example.

NOTE: The workaround for this is hacky as the angular bootstap is postponed in with a setTimeout, so consider transforming jsx in a build step.

Usage with webpack and AngularJS < 1.3.14

CommonJS support was added to AngularJS in version 1.3.14. If you use webpack and need to support AngularJS < 1.3.14, you should use webpack's exports-loader so that require('angular') returns the correct value. Your webpack configuration should include the following loader config:

...
module: {
  loaders: [
    {
      test: path.resolve(__dirname, 'node_modules/angular/angular.js'),
      loader: 'exports?window.angular'
    }
  ]
},
...

Developing

Before starting development run

npm install
bower install

Build minified version and run tests with

grunt

Continually run test during development with

grunt karma:background watch

Running the examples

The examples in the examples/ folder use bower_components. To install these first install bower on your machine

npm install --global bower

Then install the bower components

bower install

The examples need to be run on a local webserver like https://www.npmjs.com/package/http-server.

Run the examples by starting a webserver in the project root folder.

Community

Maintainers

  • Kasper Bøgebjerg Pedersen (@kasperp)
  • David Chang (@davidchang)

Contributors

  • Matthieu Prat (matthieuprat)
  • @Shuki-L
  • Fabien Rassinier (@frassinier)
  • Guilherme Hermeto (@ghermeto)
  • @thorsten
  • @katgeorgeek
  • @rosston
  • Tihomir Kit (@pootzko)
  • Alexander Beletsky (@alexanderbeletsky)
  • @matthieu-ravey
  • @ethul
  • Devin Jett (@djett41)
  • Marek Kalnik (@marekkalnik)
  • @oriweingart
  • Basarat Ali Syed (@basarat)
  • Rene Bischoff (@Fjandin)
  • Zach Pratt (@zpratt)
  • Alex Abenoja (@aabenoja)
  • @villesau
  • @bdwain
  • @onumossn

NPM DownloadsLast 30 Days