-
First, ensure you have AngularJS and React dependencies installed in your project:
npm install angular react
-
In your React component, create a container element (e.g., a div) where you will render the AngularJS code:
import React, { useRef, useEffect } from 'react';
const AngularJSComponentWrapper = () => {
const angularRef = useRef(null);
useEffect(() => {
// Load AngularJS library dynamically
const script = document.createElement('script');
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.2/angular.min.js';
script.async = true;
document.body.appendChild(script);
// Wait for AngularJS to load
script.onload = () => {
// Bootstrap AngularJS manually
angular.bootstrap(angularRef.current, ['YourAngularJSApp']);
};
// Clean up AngularJS when React component unmounts
return () => {
document.body.removeChild(script);
if (angularRef.current) {
angularRef.current.innerHTML = '';
}
};
}, []);
return <div ref={angularRef} />;
};
export default AngularJSComponentWrapper;
-
Create an AngularJS module and component in a separate file (e.g., angularComponent.js):
angular.module('YourAngularJSApp', []).component('angularComponent', {
template: '<h2>AngularJS Code</h2>',
});
-
In your AngularJS application's entry file (e.g., index.html), include the compiled React component and mount it:
<!-- Include the React app's bundle -->
<script src="/path/to/react-app-bundle.js"></script>
<!-- Mount the React component embedding the AngularJS code -->
<div id="react-app"></div>
<script>
// Mount the React component
ReactDOM.render(<AngularJSComponentWrapper />, document.getElementById('react-app'));
</script>
Replace /path/to/react-app-bundle.js with the actual path to your React application build bundle.
-
Start your AngularJS project, and you should see both the React and AngularJS code rendering properly.