How to do it...

For now, in this recipe, let's first install Electron, and then in the later recipes, we'll see how we can turn one of our React apps into a desktop program.

I started out with a copy of the repository from Chapter 8, Expanding Your Application, to get the countries and regions app, the same we also used for an RN example. It just so happens that you can work perfectly well with Electron with a CRA-built app, without even needing to eject it, so that's what we'll do here. First, we need to install the basic Electron package, so in the same directory where we wrote our React app, we'll execute the following command:

npm install electron --save-dev

Then, we'll need a starter JS file. Taking some tips from the main.js file at https://github.com/electron/electron-quick-start, we'll create the following electron-start.js file:

// Source file: electron-start.js

/* @flow */

const { app, BrowserWindow } = require("electron");

let mainWindow;

const createWindow = () => {
mainWindow = new BrowserWindow({
height: 768,
width: 1024
});
mainWindow.loadURL("http://localhost:3000");
mainWindow.on("closed", () => {
mainWindow = null;
});
};

app.on("ready", createWindow);

app.on("activate", () => mainWindow === null && createWindow());

app.on(
"window-all-closed",
() => process.platform !== "darwin" && app.quit()
);

Here are some points to note regarding the preceding code snippet:

  • This code runs in Node, so we are using require() instead of import
  • The mainWindow variable will point to the browser instance where our code will run
  • We'll start by running our React app, so Electron will be able to load the code from http://localhost:3000

In our code, we also have to process the following events:

  • "ready" is called when Electron has finished its initialization, and can start creating windows.
  • "closed" means your window was closed; your app might have several windows open, so at this point you should delete the closed one.
  • "window-all-closed" implies your whole app was closed. In Windows and Linux, this means quitting, but for macOS, you don't usually quit applications, because of Apple' s usual rules.
  • "activate" is called when your app is reactivated, so if the window had been deleted (as in Windows or Linux), you have to create it again.
The complete list of events that Electron can emit is at https://github.com/electron/electron/blob/master/docs/api/app.md; check it out. 

We already have our React app in place, so we just need a way to call Electron. Add the following script to package.json, and you'll be ready:

 "scripts": {
"electron": "electron .",
.
.
.

We are set; let's see how it all comes together.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.248.208