React

React is a popular library for building user interfaces for both web and native applications.

Extension.js offers built-in support for React and JSX. To use React in your extension, ensure that React and React-DOM are added as a dependency or devDependency in your package.json. Once set up, you're ready to build your extension with React!

Starter React Template

Extension.js includes a New Tab React template, which is ideal for creating extensions with a new tab page built in React. This is the quickest way to integrate React with your extension.

React Extension Template

Try it yourself

npm
pnpm
yarn
npx extension@latest create my-extension --template=new-react

React + Content Script Template

Alternatively, Extension.js supports a Content Script React template, allowing you to inject React into web pages as part of your extension's content scripts.

React + Content Script Template

Try it yourself

npm
pnpm
yarn
npx extension@latest create my-extension --template=content-react

Usage With an Existing Extension

If you'd like to integrate React into an existing extension, follow these steps:

Installation

Install the required dependencies:

npm
yarn
pnpm
bun
npm install react react-dom @types/react @types/react-dom --save-dev

Configuration

Extension.js expects React files to use the following file extensions:

  • If TypeScript is not enabled: *.jsx
  • If TypeScript is enabled: *.tsx

Usage Examples

In a New Tab Extension

To use React in a new tab extension, include it in your HTML file as a <script>:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>New Extension</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this extension.</noscript>
    <div id="root"></div>
  </body>
  <script src="./Index.jsx"></script>
</html>
// Index.jsx;
import React from "react";
import ReactDOM from "react-dom/client";
import MyExtension from "./MyExtension";

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(
  <React.StrictMode>
    <MyExtension />
  </React.StrictMode>,
);
// MyExtension.jsx;
export default function MyExtension() {
  return <h1>Hello, Extension!</h1>;
}

In a content_script File

For content scripts, you can inject React into the page by dynamically creating an HTML element and rendering React into it:

import React from "react";
import ReactDOM from "react-dom/client";

// Dynamically import styles for content scripts
import("./content.css");
import MyExtension from "./MyExtension";

setTimeout(initial, 1000);

function initial() {
  // Create a new div element and append it to the document body
  const rootDiv = document.createElement("div");
  rootDiv.id = "extension-root";
  document.body.appendChild(rootDiv);

  // Create a root and render the <MyExtension /> component
  const root = ReactDOM.createRoot(rootDiv);
  root.render(<MyExtension />);
}

Next Steps