Integration Patterns
Third-party library integration, jQuery migration, vanilla JS interop, and micro-frontends.
Overview
React often needs to integrate with existing codebases and third-party libraries.
Key Concepts
- Wrapper Components — Adapt non-React libraries
- jQuery Migration — Gradual migration from jQuery to React
- Vanilla JS Interop — Use refs to interact with DOM
- Micro-Frontends — Independent React apps in one page
- Module Federation — Share modules between apps at runtime
Code Examples
// jQuery wrapper component
function jQueryDataTable({ options, ...props }) {
const tableRef = useRef(null);
const instanceRef = useRef(null);
useEffect(() => {
instanceRef.current = $(tableRef.current).DataTable(options);
return () => instanceRef.current?.destroy();
}, []);
useEffect(() => {
instanceRef.current?.ajax.reload();
}, [props.data]);
return <table ref={tableRef} {...props} />;
}
// Chart.js wrapper
function Chart({ type, data, options }) {
const canvasRef = useRef(null);
const chartRef = useRef(null);
useEffect(() => {
if (chartRef.current) {
chartRef.current.data = data;
chartRef.current.update();
} else {
chartRef.current = new Chart(canvasRef.current, { type, data, options });
}
return () => chartRef.current?.destroy();
}, [data, options]);
return <canvas ref={canvasRef} />;
}
// Micro-frontend host
function MicroFrontend({ name, host, history }) {
const containerRef = useRef(null);
useEffect(() => {
const scriptId = `micro-frontend-${name}`;
const load = async () => {
const remoteUrl = `${host}/remoteEntry.js`;
await new Promise((resolve) => {
const script = document.createElement('script');
script.src = remoteUrl;
script.id = scriptId;
script.onload = resolve;
document.head.appendChild(script);
});
const { mount, unmount } = window[`micro-frontends-${name}`];
mount(containerRef.current, { history });
return () => unmount(containerRef.current);
};
load();
}, [name, host]);
return <div ref={containerRef} />;
}
Practice
Integrate a jQuery plugin into a React app and plan a migration strategy.