Electron is a popular framework that allows developers to build cross-platform desktop applications using web technologies like HTML, CSS, and JavaScript. By combining Electron with React, developers can create rich, interactive desktop applications with a modern user interface. This chapter explores how to integrate React with Electron, the benefits of using React in desktop applications, and advanced techniques to optimize performance.
Electron is an open-source framework developed by GitHub. It allows developers to build desktop applications using web technologies and packages them into cross-platform applications for Windows, macOS, and Linux.
While Electron provides a platform to build desktop applications, React helps in creating modular, reusable, and maintainable user interfaces. The combination of Electron and React leads to:
Ensure that you have Node.js installed on your system. To verify, run:
node -v
npm -v
1.Initialize a new React project: Start by creating a React app using create-react-app
.
npx create-react-app my-electron-app
cd my-electron-app
2.Install Electron: Install Electron as a dependency
npm install electron --save
3.Configure Electron: Create the necessary Electron files to launch the application.
Create a file public/electron.js:
const { app, BrowserWindow } = require('electron');
const path = require('path');
const isDev = require('electron-is-dev');
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
},
});
mainWindow.loadURL(
isDev
? 'http://localhost:3000'
: `file://${path.join(__dirname, '../build/index.html')}`
);
mainWindow.on('closed', () => (mainWindow = null));
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (mainWindow === null) {
createWindow();
}
});
4.Update package.json
: Modify the package.json
to include Electron’s start command and the build settings.
"main": "public/electron.js",
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"electron-dev": "concurrently \"npm start\" \"wait-on http://localhost:3000 && electron .\"",
"electron-pack": "npm run build && electron-packager ."
},
You’ll also need to install concurrently
and wait-on
:
npm install concurrently wait-on --save-dev
Run the Electron app: Use the following command to start the development server and launch Electron.
npm run electron-dev
React allows you to break down the UI into components, which can be reused throughout the application. Let’s create a simple component.
// src/components/HelloWorld.js
import React from 'react';
const HelloWorld = () => {
return Hello, Electron + React!
;
};
export default HelloWorld;
Now import and use this component in App.js
:
import React from 'react';
import HelloWorld from './components/HelloWorld';
function App() {
return (
);
}
export default App;
One of the significant advantages of Electron is that it allows access to Node.js APIs. This can be especially useful for interacting with the file system or managing operating system resources. Here’s how to use Node.js within a React component.
// src/components/FileReader.js
import React, { useState } from 'react';
const { dialog } = window.require('electron').remote;
const fs = window.require('fs');
const FileReader = () => {
const [fileContent, setFileContent] = useState('');
const openFile = () => {
dialog.showOpenDialog({ properties: ['openFile'] }).then((file) => {
if (!file.canceled) {
fs.readFile(file.filePaths[0], 'utf-8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
setFileContent(data);
});
}
});
};
return (
{fileContent}
);
};export default FileReader;
This example demonstrates how to open a file dialog, read a file using Node.js, and display its contents.
Once your application is ready, you can package it into an executable format using Electron’s packaging tools.
Electron Packager is a tool that packages your Electron app into binaries for Windows, macOS, and Linux.
Install Electron Packager:
npm install electron-packager --save-dev
Then, run the following command to build and package your app:
npm run electron-pack
This will create a folder containing the packaged app for your target platform.
Electron has two processes: the main process (which manages the application’s lifecycle and native operations) and renderer processes (which handle the UI). To communicate between these processes, you can use IPC (Inter-Process Communication).
Here’s how to send messages between the main and renderer processes:
electron.js
(main process):
const { ipcMain } = require('electron');
ipcMain.on('message-from-renderer', (event, message) => {
console.log('Message received:', message);
});
const { ipcRenderer } = window.require('electron');
ipcRenderer.send('message-from-renderer', 'Hello from React!');
Electron apps can be resource-intensive because they run Chromium alongside Node.js. To optimize performance:
React.memo
).React.lazy
and Suspense
.Electron-builder
for better optimization during packaging.By integrating React with Electron, you can build powerful, cross-platform desktop applications using the same tools you’d use for web development. With the flexibility of Electron for accessing system resources and React’s component-based architecture, developers can create modern desktop apps quickly and efficiently. Happy coding !❤️