Hello Sitecorians! 👋
In this blog, I will take a React external component in Sitecore Content Hub apart, piece by piece: the entry point, the context it gets, the configuration, API calls, events, styling, building and uploading. If you have copied a sample before and wondered what each part does, this one is for you.
So, let's get started! 😊
What Is a React External Component?
An external component is your own JavaScript, running on a Content Hub page next to the built-in components. Content Hub loads your bundle, gives it an HTML element, and lets you draw anything inside it.
Use one when the out-of-the-box components cannot do what the business needs. A few examples:
- A custom button that calls an API or starts a process.
- A warning or confirmation before an action, like a download.
- A dashboard or a chart on the asset details page.
- A full custom page, like your own search experience.
If a page component and its settings can do the job, use that instead. An external component is code you own, so you also own testing it after every upgrade.
At a Glance
createExternalRoot once. After that, it calls render() with the context, and unmount() when the user leaves. Everything else, like API calls, events and styles, happens inside your bundle. The parts below follow this picture from top to bottom.Part 1: The Entry Point
Every external component is an ES module with one default export: a function called createExternalRoot. Content Hub calls it once, with the HTML element your component lives in. The function returns an object with two methods, render and unmount.
Here is the smallest useful component, with React 18:
import React from "react";
import { createRoot, type Root } from "react-dom/client";
import { App } from "./App";
export default function createExternalRoot(container: HTMLElement) {
// Runs once: set up things here, not in render()
const root: Root = createRoot(container);
return {
render(context: any) {
root.render(<App context={context} />);
},
unmount() {
root.unmount();
}
};
}Three things to know:
- Setup goes outside
render(). Create the React root, styles and listeners once, in the function body. render()can run more than once. Content Hub calls it again when the context changes. Make it safe to repeat: render the same root again, don't create a new one.unmount()must clean up everything. Unmount React, remove listeners, clear timers. Otherwise they keep running after the user leaves the page.
In newer versions, createExternalRoot also gets a second argument, clientBuilder, which builds an SDK client for you (see Part 4).
Part 2: The Context
The object passed to render() is the context. It is how Content Hub talks to your component.
Property | What it holds |
|---|---|
| Your custom JSON from the component's Configuration (empty object by default) |
| Where the component is: |
| The current entity on a details page, or |
| The signed-in user: |
| Helpers for search, selection, the details page and notifications |
| A pre-authenticated SDK client |
| The Material UI theme (fonts, colors) |
| Puts a Content Hub icon into an element |
entity is null when the component is not on a details page, so always check it first:
function App({ context }: { context: any }) {
const entityId = context.options?.entityId;
if (!context.entity) return <p>Open an asset to see this panel.</p>;
return <p>Asset {entityId}, viewed by {context.user?.userName}</p>;
}Tip: When you start, log the context once in
render()withconsole.log(context). It shows exactly what your version of Content Hub passes.
Part 3: The Configuration
The Configuration section of the component holds your own JSON. It arrives as context.config.
{
"pageSize": 50,
"apiUrl": "https://my-function.azurewebsites.net/api/start",
"showBetaNotice": true
}const pageSize = Number(context.config?.pageSize ?? 25);
const showNotice = context.config?.showBetaNotice === true;Put everything that differs between environments or businesses here: entity IDs, URLs, feature flags, texts. The same bundle then works on DEV, QA and production, and a change does not need a new build.
Always give a default. The configuration can be empty, and someone may misspell a key.
Part 4: Talking to Content Hub
There are three ways, and a real component often uses all three.
1. The api object. It controls things that are already on the page:
context.api.notifier.notifySuccess("Saved!");
context.api.details.reloadEntity(entityId, true);
context.api.search.activate("MySearchIdentifier");
context.api.selection.addToSelection([assetId], "MySelectionPool");2. The SDK client. For queries and saving entities, use the JavaScript SDK (@sitecore/sc-contenthub-webclient-sdk). The client in the context is already signed in. Sitecore recommends creating only the parts of the client you need, through clientBuilder, to keep the bundle small.
3. The REST API with fetch. The component runs in the user's browser session, so a plain fetch to /api/... works with the user's own permissions and no token:
const response = await fetch(`/api/entities/${entityId}`, { headers: { Accept: "application/json" } });
const asset = await response.json();For calls that change data (POST, PUT, DELETE), I also send the page's request verification token. Without it, my write calls were rejected:
function verificationToken(): string {
const input = document.querySelector<HTMLInputElement>('input[name="__RequestVerificationToken"]');
if (!input?.value) throw new Error("Request token is missing. Refresh the page and try again.");
return input.value;
}
await fetch("/api/...", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"X-Requested-By": verificationToken()
},
body: JSON.stringify(payload)
});Part 5: Events
Content Hub sends browser events on window when things happen on the page. For example, ENTITY_SAVED fires when an entity is saved:
const onEntitySaved = (evt: Event) => {
const { definitionName, id } = (evt as CustomEvent<{ definitionName: string; id: number }>).detail;
if (id === context.options?.entityId) reloadMyData();
};
window.addEventListener("ENTITY_SAVED", onEntitySaved);
// and in unmount():
window.removeEventListener("ENTITY_SAVED", onEntitySaved);Check the id in the event. Every save on the page fires it, not only the entity you care about.
Part 6: Styling
Your component sits inside the Content Hub page, so its CSS and the page's CSS can affect each other. There are two safe ways:
Scope every rule with a unique class or ID on your root element:
.my-component .card { padding: 16px; }Or use a Shadow DOM, which fully separates your styles from the page. This is what I use for larger components:
import styles from "./styles.css"; // bundled as a string
export default function createExternalRoot(container: HTMLElement) {
const shadowRoot = container.shadowRoot || container.attachShadow({ mode: "open" });
const style = document.createElement("style");
style.textContent = styles;
const mount = document.createElement("div");
shadowRoot.replaceChildren(style, mount);
const root = createRoot(mount);
return {
render(context: any) { root.render(<App context={context} />); },
unmount() { root.unmount(); shadowRoot.replaceChildren(); }
};
}To match the Content Hub look, use its CSS variables, with a fallback: color: var(--color-cyan, #00a0b0). You can also read colors from context.theme. Sitecore advises not to pass the theme straight into your own Material UI components, because your MUI version can differ from Content Hub's.
Note: A popup or dialog inside your component's element can end up behind other page parts, like Quick View. If it must be on top of everything, append it to
document.bodyand remove it inunmount().
Part 7: Error Handling
If your component throws while rendering, React removes it and the user sees an empty space. Wrap the app in an error boundary so the user sees a clear message instead:
class ErrorBoundary extends React.Component<React.PropsWithChildren, { failed: boolean }> {
state = { failed: false };
static getDerivedStateFromError() {
return { failed: true };
}
componentDidCatch(error: Error) {
console.error("MyComponent:", error);
}
render() {
return this.state.failed
? <p role="alert">This panel could not be displayed. Refresh the page and try again.</p>
: this.props.children;
}
}
// in render():
root.render(<ErrorBoundary><App context={context} /></ErrorBoundary>);Start every console message with your component's name. Then you can filter the browser console on it when something goes wrong.
Part 8: Building the Bundle
Content Hub needs one JavaScript file in ES module format. I use esbuild, because it is fast and needs almost no setup:
npm install react react-dom
npm install --save-dev esbuild typescript @types/react @types/react-domA small build.mjs:
import { build } from "esbuild";
import { readFile } from "node:fs/promises";
// Turns "import styles from './styles.css'" into a string
const cssAsString = {
name: "css-as-string",
setup(b) {
b.onLoad({ filter: /\.css$/ }, async ({ path }) => ({
contents: `export default ${JSON.stringify(await readFile(path, "utf8"))};`,
loader: "js"
}));
}
};
await build({
entryPoints: ["src/index.tsx"],
outfile: "dist/my-component.js",
bundle: true,
format: "esm",
target: ["es2020"],
jsx: "automatic",
minify: true,
plugins: [cssAsString]
});Run it with node build.mjs. React is bundled into the file, so the component does not depend on the React version Content Hub uses.
A folder layout that grows well:
my-component/
src/
index.tsx ← createExternalRoot only
App.tsx ← the UI
api/ ← fetch calls
components/ ← smaller UI parts
styles.css
tests/
build.mjs
package.jsonKeep index.tsx small. It should only connect Content Hub to your app; the logic lives in the other files, where you can test it.
Part 9: Uploading and Adding It to a Page
The bundle can be a portal asset in Content Hub, or a file on a CDN. Then add it to a page:
- Go to Manage → Pages and open the page.
- On the Layout tab, add an External component where you want it.
- Open the component's details.
- Choose the code source: From path for a CDN URL, or From asset to pick the uploaded bundle.
- In the Configuration section, paste your JSON.
- Click Save and close.
[Screenshot: the External component settings with the code source and Configuration]
When you upload a new version, the browser may still use the old file. Do a hard refresh, or add a version to the file name (for example my-component-v2.js).
Common Mistakes and Tips
These are the problems I ran into most often:
Problem | Why it happens | Fix |
|---|---|---|
Click handlers on built-in menus never fire | Content Hub draws menus only when they open, after your | Listen on |
Listeners fire twice, or after leaving the page |
| Add listeners once; remove them in |
Your CSS changes other parts of the page | Unscoped selectors | Scope every rule, or use a Shadow DOM |
The component broke after an upgrade | It depends on Content Hub's HTML ( | Prefer |
The old version still loads | The browser cached the bundle | Hard refresh, or version the file name |
A value works on DEV but not on QA | An ID or URL is hardcoded | Move it to the Configuration |
And a few habits that save time:
- Fail safe. If a check fails (for example, an API call), choose the safer behavior and log it. Don't break the page.
- Test the logic outside Content Hub. Keep API calls and rules in plain functions, and test them with a tool like Vitest. Then only the wiring needs testing in Content Hub.
- Keep the bundle small. Import only what you use. Load big, rarely used libraries (like a PDF viewer) as a separate bundle, only when needed.
Sources
- Configure the external component
- Use subscribing events
- Add an external component
- Developing external components (Sitecore Accelerate)
Conclusion
A React external component has a small shape: createExternalRoot sets things up once, render() draws with the context Content Hub gives it, and unmount() cleans up. Around that sit the configuration for values that change, the api, SDK and REST calls to talk to Content Hub, scoped styles, an error boundary, and a one-file ESM build. Once you know these parts, any custom page or panel is the same pattern with a different App.
I hope this helps you in your Content Hub journey! If you have any questions, feel free to drop a comment below. 😊
Stay tuned for more! 👋
