How to integrate React into an Electron Forge project

The following guide has been tested with React 18, Babel 7, and Webpack 5.

To integrate React into an Electron Forge project, follow these steps:

  1. Create Your Electron App with Electron Forge:
    Scaffold a new app using the following command:
    npm init electron-app@latest my-new-app -- --template=webpack

    You should use the webpack-typescript template instead if you are using TypeScript in your project.

  2. Add React Dependencies:
    Install the necessary packages to your devDependencies so that JSX and other React features can be used properly:
    npm install --save-dev @babel/core @babel/preset-react babel-loader

  3. Configure Webpack:
    Set up the babel-loader module with the React preset in your webpack.rules.js file

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    // webpack.rules.js
    module.exports = [
    // ... existing loader config ...
    {
    test: /\.jsx?$/,
    use: {
    loader: "babel-loader",
    options: {
    exclude: /node_modules/,
    presets: ["@babel/preset-react"],
    },
    },
    },
    // ... existing loader config ...
    ];
  4. Add Basic React Packages:
    Install the following React packages to your dependencies:
    npm install --save react react-dom

  5. Integrate React Code:
    You can now start writing and using React components in your Electron app.
    Here’s a minimal example of how to add React code:

    1
    2
    3
    4
    5
    // src/app.jsx
    import React from "react";
    import { createRoot } from "react-dom/client";
    const root = createRoot(document.body);
    root.render(<h2>Hello from React!</h2>);
    1
    2
    3
    // src/renderer.js
    // Import your React components here if needed
    import "./app";
  6. Add JSX support in TypeScript
    If you prefer to use TypeScript over JavaScript, then you need to enable JSX support in the tsconfig.json file:

    1
    2
    3
    4
    5
    6
    7
    {
    "compilerOptions": {
    "jsx": "react"
    // ....
    }
    // ...
    }