React.js with Electron.js

Connect React.js with Electron.js. Create desktop application with React and Electron.

At first go to your command prompt and type there:

npx create-react-app@latest "your-apps-name"

press enter, then after installing react, type

npm install electron electron-builder wait-on concurrently --dev

press enter, then after installing react, type

npm install electron-is-dev

Then in your public folder create Main.js file and paste there the boilerplate code below:

const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;

const path = require('path');
const url = require('url');
const isDev = require('electron-is-dev');

let mainWindow;

function createWindow() {
  mainWindow = new BrowserWindow({width: 600, height: 600});
  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();
  }
});

We’re adding it in the “public” folder instead of “src” so it can get copied to the “build” folder as it is. This is needed for the production version.

Add the “main” property to package.json and point it to the electron file:
"main": "public/main.js",
code image

Then in command prompt type

npm install cross-env

Then in package.json file add this npm script to run the dev version inside scripts:

  “electron-dev”: “concurrently \”cross-env BROWSER=none npm start\” \”wait-on http://localhost:3000 && electron .\””

code image

Now, in your terminal in VS Code (ctrl + j will open terminal) type npm run electron-dev and press enter.

If you did everything right, the dekstop app window will appear, like below:

electron image

Posted by Edgar Hovhannisyan

Comments

Your email address will not be published. Required fields are marked *