Categories
data science

Electron and React App – the basics

Essentials for getting a desktop app up and running using Electron and React.

JUST THE SETUP

For the purpose of this tutorial we’ll call the new app “newapp”

Start by creating a React app

npx create-react-app newapp

Now you need to cd into the newly created directory and install Electron and the other stuff. Both wait-on and concurrently are important for running the app.

cd newapp

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

npm install electron-is-dev

Add a main.js to the public folder and put this in there

const {app, BrowserWindow} = require('electron')

function createWindow(){

  // declare the main window
  win = new BrowserWindow({
    width: 1200,
    height: 700
  })

  // load the React local host on main window
  win.loadURL("http://localhost:3000/")

}

app.on('ready', createWindow)

Now you want to open the package.json file and add two key things.

First you want to point it to the main.js file you just created

"main": "public/main.js"

Then you want to add a script to run both React and Electron

    "electron-dev": "concurrently \"BROWSER=none npm run start\" \"wait-on http://localhost:3000 && electron .\""

Basically, your package.json file should look like this.

{
  "name": "newapp",
  "version": "0.1.0",
  "private": true,
  "main": "public/main.js",
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "concurrently": "^5.1.0",
    "electron": "^8.2.3",
    "electron-builder": "^22.5.1",
    "electron-dev": "^1.0.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-scripts": "3.4.1",
    "wait-on": "^4.0.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "electron-start": "concurrently \"BROWSER=none npm run start\" \"wait-on http://localhost:3000 && electron .\""
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

With lines 5 and 24 being the ones you just added.

Now you can run the app to make sure it works

npm run electron-start

and you should get a window like this one.

If so, it means everything works.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s