DEV Community

Selvi Parasakthi K
Selvi Parasakthi K

Posted on

How to Use React Components Inside Angular (Step-by-Step Guide)

In real-world projects, teams often work with multiple frameworks like React and Angular.

But what if you already built a component in React and want to reuse it inside an Angular application?

πŸ‘‰ Do you need to rewrite everything?
πŸ‘‰ Or is there a smarter way?

Good news: You can directly use React components inside Angular using Web Components.

In this blog, I’ll walk you through a step-by-step process with clear explanations, so even if you try this for the first time, it will work.


🧠 Understanding the Idea First

Before jumping into code, let’s understand what we are doing.

React components are not directly compatible with Angular because:

  • React uses a Virtual DOM
  • Angular uses its own template system

So they don’t β€œtalk” to each other natively.

πŸ’‘ Solution: Web Components

Web Components are browser-native custom HTML elements.

Example:

<random-picker></random-picker>
Enter fullscreen mode Exit fullscreen mode

Once we convert a React component into a Web Component:

  • Angular treats it like a normal HTML tag
  • No framework conflict
  • Fully reusable

πŸ›  Step 1: Create a React Project

We’ll first build our React component separately.

npm create vite@latest random-picker
cd random-picker
npm install
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Why Vite?

  • Fast build tool
  • Simple configuration
  • Perfect for creating reusable components

πŸ“¦ Step 2: Install r2wc

We use a library to convert React β†’ Web Component.

npm install @r2wc/react-to-web-component
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Why this library?

Normally, converting React into a Web Component requires a lot of manual work.

This package:

  • Wraps your React component
  • Handles lifecycle
  • Maps props automatically

βš›οΈ Step 3: Create a Simple React Component

Now let’s create a clean and minimal component (no CSS, so beginners can focus on logic).

// src/components/RandomPicker.tsx

import { useState } from "react";

type Props = {
  items?: string[];
  title?: string;
  onResult?: (value: string) => void;
};

export default function RandomPicker({
  items = [],
  title = "Pick one",
  onResult,
}: Props) {
  const [result, setResult] = useState("");

  // Function to pick a random item
  const pick = () => {
    if (!items.length) return;

    const randomItem =
      items[Math.floor(Math.random() * items.length)];

    setResult(randomItem);

    // send result back (optional)
    onResult?.(randomItem);
  };

  return (
    <div>
      <h3>{title}</h3>
      <button onClick={pick}>Pick Random</button>
      {result && <p>Result: {result}</p>}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

🧩 What’s happening here?

  • items β†’ list of values
  • title β†’ heading
  • onResult β†’ callback function
  • pick() β†’ selects a random item

This is just a normal React component.


πŸ” Step 4: Convert React to Web Component

Now comes the important part - converting your React component into something Angular can understand.

// src/random-picker-wc.ts

import r2wc from "@r2wc/react-to-web-component";
import RandomPicker from "./components/RandomPicker";

const RandomPickerWC = r2wc(RandomPicker, {
  props: {
    items: "json",
    title: "string",
    onResult: "function",
  },
});

// Register as HTML element
customElements.define("random-picker", RandomPickerWC);
Enter fullscreen mode Exit fullscreen mode

πŸ” Deep Explanation

πŸ“Œ React β†’ Angular Compatibility Problem

React and Angular are built on completely different architectures:

  • React uses a Virtual DOM
  • Angular uses template-driven rendering

Because of this difference, Angular cannot directly render a React component.
To make them work together, we need a framework-independent layer β€” this is where Web Components come in.

πŸ“Œ Role of r2wc()

The r2wc function acts as a bridge between React and the browser.

  • It wraps your React component
  • Converts it into a native Custom Element
  • Handles mounting, updating, and unmounting internally

After this conversion, your React component behaves like a normal HTML tag.

πŸ‘‰ In simple terms:

React Component β†’ Web Component β†’ Usable in Angular
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ Why We Define props

Web Components don’t receive JavaScript props like React.
They receive HTML attributes, which are always strings.

So we must explicitly define how each prop should be interpreted.

props: {
  items: "json",
  title: "string",
  onResult: "function",
}
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ Understanding Each Prop Type

  • json
    • Used when passing arrays or objects
    • Converts string β†’ actual JavaScript data
    • Example: "['Apple','Mango']" β†’ ["Apple","Mango"]
  • string
    • Used for simple text values
    • Passed directly without transformation
  • function
    • Used for callbacks/events
    • Enables communication from React β†’ Angular

πŸ“Œ Role of customElements.define()

customElements.define("random-picker", RandomPickerWC);
Enter fullscreen mode Exit fullscreen mode

This step registers your component in the browser.

After registration:

  • <random-picker> becomes a valid HTML element
  • It can be used anywhere (Angular, HTML, etc.)

Without this step:

  • The browser will not recognize your component
  • Nothing will render

Now the browser understands this element.


⚑ Step 5: Build React Project (Using vite)

Instead of doing a normal build, we configure Vite to generate a reusable Web Component bundle.

🧩 Create Vite Config

// vite.config.ts

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [react()],
  build: {
    lib: {
      entry: "src/random-picker-wc.ts",
      name: "RandomPicker",
      fileName: "random-picker",
      formats: ["es"],
    },
    cssCodeSplit: false,
  },
});
Enter fullscreen mode Exit fullscreen mode
npm run build
Enter fullscreen mode Exit fullscreen mode

This generates a file inside the dist folder:

dist/random-picker.js
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ This file contains your Web Component ready to use in Angular.


πŸ…°οΈ Step 6: Setup Angular Project

ng new angular-app
cd angular-app
Enter fullscreen mode Exit fullscreen mode

πŸ”— Step 7: Load React Script in Angular

Open angular.json

Add your React build file:

"scripts": [
  "src/assets/random-picker.js"
]
Enter fullscreen mode Exit fullscreen mode

Make sure you copy random-picker.js from the React dist folder into Angular src/assets/

πŸ‘‰ Why this step?

Angular doesn’t know about your React component.
So we manually load the script globally.


⚠️ Step 8: Enable Custom Elements in Angular

Angular throws an error for unknown HTML tags.

To fix that:

import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.html',
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
export class App {}
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Why?

This tells Angular:

β€œDon’t complain about unknown elements β€” I know what I’m doing.”


🧩 Step 9: Use React Component in Angular

Now you can use your React Web Component just like a normal HTML element in Angular.

<random-picker
  title="Fruits Picker"
  [attr.items]="'[\"Apple\",\"Mango\",\"Orange\"]'"
></random-picker>
Enter fullscreen mode Exit fullscreen mode

πŸŽ‰ Final Result

Now your Angular app renders a React component 🎯

  • React logic runs inside
  • Angular displays it
  • Both work together seamlessly

🧾 Summary (What You Learned)

  • React and Angular are not directly compatible
  • Web Components act as a bridge
  • r2wc simplifies conversion
  • Angular can consume custom elements easily

πŸ”₯ When Should You Use This?

This approach is perfect when:

  • You want to reuse React components
  • Multiple teams use different frameworks
  • You are building a shared component library

⚠️ Common Mistakes

  • ❌ Forgetting CUSTOM_ELEMENTS_SCHEMA
  • ❌ Not adding script in angular.json
  • ❌ Passing objects instead of JSON string

πŸ™Œ Final Thoughts

This technique is extremely powerful.

Once you understand this pattern, you can:
πŸ‘‰ Use React components inside Angular applications
πŸ‘‰ Reuse UI across different projects and frameworks
πŸ‘‰ Build framework-independent UI libraries


If this helped you, feel free to ❀️ and share!

Happy coding πŸš€

Top comments (0)